How can I put a column from a SQLite table into the options of a Combobox?
-
I thought exposing the data as a QStringListModel to QML would work.
I currently have this:
main.qml:ComboBox { id: country_loaded width: 200 height: 50 model: plateModel background: Rectangle { color: mecs_white border.width: 3 border.color: mecs_white radius: 10 } }
class DataManager(QObject): def __init__(self): super().__init__() self.model = QStringListModel() def load_plate_data(self): # Connect to the SQLite database conn = sqlite3.connect('rfid_gate_system.db') cursor = conn.cursor() # Query the plates cursor.execute("SELECT plate FROM plates") plates = [row[0] for row in cursor.fetchall()] # Update the model with the plate data self.model.setStringList(plates) # Close the connection conn.close() if __name__ == "__main__": app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() data_manager = DataManager() data_manager.load_plate_data() engine.rootContext().setContextProperty("plateModel", data_manager.model) qml_file = Path(__file__).resolve().parent / "main.qml" engine.load(qml_file) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec())
getting this error:
qrc:/qt-project.org/imports/QtQuick/Controls/Windows/ComboBox.qml:65:9: Unable to assign QQmlDMAbstractItemModelData to QString
-
When using a QAbstractItemModel subclass with multiple roles as the model of a ComboBox, you need to set its
textRole
(andvalueRole
).
In your case you should addtextRole: "display"
to your ComboBox . -
-
Hell yea, it works
-
When using a QAbstractItemModel subclass with multiple roles as the model of a ComboBox, you need to set its
textRole
(andvalueRole
).
In your case you should addtextRole: "display"
to your ComboBox .This post is deleted! -
When using a QAbstractItemModel subclass with multiple roles as the model of a ComboBox, you need to set its
textRole
(andvalueRole
).
In your case you should addtextRole: "display"
to your ComboBox .@GrecKo Do you maybe also know how i can style the text in my dropdown?
-
See https://doc.qt.io/qt-6/stylesheet-examples.html#customizing-qcombobox
In theQComboBox::drop-down
section you can style text as you would do in a label -
See https://doc.qt.io/qt-6/stylesheet-examples.html#customizing-qcombobox
In theQComboBox::drop-down
section you can style text as you would do in a label@VRonin I am programming in qml.
-
@GrecKo Do you maybe also know how i can style the text in my dropdown?
@MaximBozek If you just want to change the text you can do so by setting an explicit
displayText
property. If you want to change how it is displayed you can do so by changing thecontentItem
.