0

I have a basic combo box populated with data from an sqlite3 database table:

self.langModel = QSqlTableModel(self)
self.langModel.setTable("languages")
self.langModel.setSort(self.langModel.fieldIndex("label"), Qt.AscendingOrder)
self.langModel.select()

...

self.comboLangs = QComboBox()
self.comboLangs.setModel(self.langModel)
self.comboLangs.setModelColumn(self.langModel.fieldIndex("label"))
self.layout.addRow("Language", self.comboLangs)

...

self.btnAdd = QPushButton("Add")
self.btnAdd.clicked.connect(self.addLoc)
self.btnLayout.addWidget(self.btnAdd)

...

def addLoc(self):
    pprint(vars(self.langModel.data(self.langModel.index(self.comboLangs.currentIndex(), self.langModel.fieldIndex("iso")))))

Here is the table schema:

CREATE TABLE languages ( 
    id    INTEGER PRIMARY KEY NOT NULL,
    iso   TEXT    NOT NULL,
    label TEXT    NOT NULL 
);

This just produces an empty dict {}. How do I get the selected/current item's data object from the QSqlTableModel?

cj5
  • 785
  • 3
  • 12
  • 34

1 Answers1

4

Okay figured it out (I wish the PyQt reference documentation was a little bit more specific on how to do this). Anyhow, to get the model data I needed to convert the QVariant object to either a Python object (toPyObject()) or to a tring (toString()).

print self.langModel.data(self.langModel.index(self.comboLangs.currentIndex(), self.langModel.fieldIndex("iso"))).toString()

This got me the data I needed.

cj5
  • 785
  • 3
  • 12
  • 34