[PyQt] auto-completing combo box with table view

Andreas Pakulat apaku at gmx.de
Wed Nov 28 10:56:50 GMT 2007


On 28.11.07 18:43:43, Horst Herb wrote:
> 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]

That model provides data, no matter wether the index is valid or not or
the role matches Qt.DisplayRole. That means you break the contract
between model and view.


> class MyCompleter(QCompleter):
>     def __init__(self, parent=None):
>         super(MyCompleter, self).__init__(parent)
>         model = MyCompletionModel()

Thats another bad idea, you don't keep a reference to the model so it
will disappear as soon as __init__ is done.

> class AutoCompletionTest(QDialog):
>     def __init__(self, parent=None):
>         super(AutoCompletionTest, self).__init__(parent)
>         self.combo = QComboBox()
>         self.combo.setEditable(True)
>         completer = MyCompleter()

Same thing here.

>         self.combo.setCompleter(completer)
>         layout = QVBoxLayout()
>         layout.addWidget(self.combo)
>         self.setLayout(layout)

I'm not 100% sure about the layout, it might be re-parented to self and
you don't need to keep a reference to it yourself. I guess if your gui
show up at least your fine here.

Andreas

-- 
You are magnetic in your bearing.


More information about the PyQt mailing list