PDA

View Full Version : QPushButtons and Data, Not Derived



tescrin
5th July 2012, 18:31
So I've been looking at the documentation as I clean up some code and with QActions you can (and I have) stored data so you can simply grab or update data (i.e. the data is abstracted from the action's text)

All the solutions I've seen with QPushButtons (and have implemented this far) involve deriving the data from the text of the button. This seems like a backwards way to do it as the button, even if it's an inefficient use of space, SHOULD store the data rather than the code "derive" the data from the text of the button at all times. It seems hokey to go through this process of converting a button's text to data and it doesn't feel right that the "data" isn't abstracted from the button.

Basically my question is if there's another way of doing this without subclassing the button to add a data member. Like the QAction is there a setData() member I might be missing?


P.S.
For instance: Let's say you have an EE button on a calculator. You could store the "E" in the button, but you wouldn't want to use it's text of "EE." I solved this problem by simply adding a function that deals with it called by the clicked() signal; but being able to derive any button's data with a single function cleans up the entire code by a mile. This and other similar instances are why I'm asking.

d_stranz
5th July 2012, 18:46
Why can't you use the QObject::property() and QObject::setProperty() methods for this? You can store named QVariant data where the name is completely independent of the text of the button. Since all widgets are derived from QObject, this is a completely general solution. It also allows for dynamic changes to the property, unlike trying to derive something from static text.

The other way to implement this is outside of the widget entirely, by creating lookup tables (an std::map<> or QMap<>) that associate your data with the widget's pointer value.

tescrin
5th July 2012, 20:49
:D Very cool stuff. Thank you! This was exactly the type of answer I expected, was looking for, and was hoping for. There's just a lot of functions to look through and I hadn't checked QObject yet. I figured since QAction had it's own "data" member, that it might not be worth looking through the entire hierarchy for something that wouldn't be there. I'm guessing then that the QAction's data member is more of a convenience, is more powerful, and/or just so you can store more pieces of data into an action.

Thanks again!