[PyQt] auto-completing combo box with table view

Horst Herb subscriptions at gnumed.net
Wed Nov 28 07:43:43 GMT 2007


After studying the PyQT documentation for an hour, I remain confused
I have a simple task: a combo widget shall start auto-completing text input 
from a database table, and present options in a table view (column-separated 
list of database rows)

This must be a very common task, so I am puzzled that it should require so 
much code - maybe I am missing something?

What is for example wrong with this code that doesn't even start 
autocompleting:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyCompletionModel(QAbstractTableModel):
    #dummy instead of database data
    def __init__(self, parent=None):
        super(MyCompletionModel, self).__init__(parent)
        self.rows = [(1,"Abraham","Alfred"), (2,"Bull","Bill"), 
(3,"Cesar", "Charles")]
    
    def rowCount(self, parent = QModelIndex()):
        return len(self.rows)
    
    def columnCount(self, parent = QModelIndex()):
        return len(self.rows[0])
    
    def data(self, index, role=Qt.DisplayRole):
        return self.rows[index]
    
class MyCompleter(QCompleter):
    def __init__(self, parent=None):
        super(MyCompleter, self).__init__(parent)
        model = MyCompletionModel()
        self.setModel(model)
        self.setCompletionColumn(1)

class AutoCompletionTest(QDialog):
    def __init__(self, parent=None):
        super(AutoCompletionTest, self).__init__(parent)
        self.combo = QComboBox()
        self.combo.setEditable(True)
        completer = MyCompleter()
        self.combo.setCompleter(completer)
        layout = QVBoxLayout()
        layout.addWidget(self.combo)
        self.setLayout(layout)


app = QApplication(sys.argv)
dlg = AutoCompletionTest()
dlg.show()
app.exec_()


I would be most grateful for any hints into the right direction,
Horst


More information about the PyQt mailing list