Qt equivalent of .NET data binding?
Is there an equivalent of .NET's data binding in Qt?
I want to populate some combo boxes and other widgets with QStrings that refer to specific entities in my database. How开发者_运维问答ever, it would be cleaner if I could bind the data to these strings rather than either querying the database again based off of a new combobox selection or some other scheme based off of building my own index of entities that would be searched with the QStrings.
The best I've come up with is to derive these entities from QString and pushing them into the widgets this way, but I've yet to actually try it. I'm not sure if it will work the way I want it to, and it seems like a nasty hack.
If there is no data binding, what do you suggest?
Thank you.
As the user nonchalant mentioned in a comment you can use the QDataWidgetMapper
class.
This is quite an easy way of binding arbitrary widgets to data that is stored in a QAbstractItemModel
.
The example on the linked page shows in a few lines of code, how you can link your data model to common used input widgets:
QDataWidgetMapper *mapper = new QDataWidgetMapper;
mapper->setModel(model);
mapper->addMapping(mySpinBox, 0);
mapper->addMapping(myLineEdit, 1);
mapper->addMapping(myCountryChooser, 2);
mapper->toFirst();
One way is using Qt Model/View Classes (with base at QAbstractItemModel), but they need that you widget inherits QAbstractItemView (this is widgets like QTableView etc.).
If you want map Qt model to set of widgets, which haven't nothing common with QAbstractItemView you can use QDataWidgetMapper, which maps separate widget to Qt Model/View indexes. But anyway, as said Aaron Digulla, you must write some boiler plate code...
Well, for combobox specifically, you can set a model. For QObjects in general you can use the notify signal for properties to connect or other non-property related signals. I think there is another way to do it but I can't recall.
精彩评论