Reputation:
I am currently working on a Qt C++ program with over 152 QPushButtons. What I would like the program to do is recolor a specific QPushButton when a specific condition is met (I have four colors for four conditions). I have arrays that keep track of each condition for each QPushButton but so far the only thing I have managed to get working is this:
ui->locker100->setStyleSheet("background-color: rgb(75, 150, 255); border-color: rgb(50, 0, 128);");
Where locker100 is a specific QPushButton. What I would like to do is concatenate a QString with an array resulting in the QPushButton's name. It would look something like this:
bool key[152];
std::fill(key, key + 152, true);
Qstring widgetName = "locker";
int input = 100;
if (key[input] == true)
{
ui->widgetName + input->setStyleSheet("background-color: rgb(75, 150, 255); border-color: rgb(50, 0, 128);");
}
However concatenating creates errors. Any feedback and specific code would be very much appreciated. Thanks!
Upvotes: 2
Views: 413
Reputation: 543
I see what you are trying to do, but you can't create identifiers by simply constructing a string that happens to be the name that you assigned the identifier. The result is still a QString and you are trying to call the method setStyleSheet() on a QString, which doesn't exist. This tells me that your understanding identifiers, types and objects in general could use some freshening up.
I believe the following code does what you are looking for though.
//Create a map of QPushButtons with a QString key.
QMap<QString, QPushButton*> buttonMap;
//As an example I create and add a QPushButton to the map
QPushButton * input100 = new QPushButton();
buttonMap.insert("input100", input100);
//Construct the key
QString button = "input100";
// In this map .value(key) returns a QPushButton * so
// we can call what ever public functions a QPushButton
// supports like this:
buttonMap.value(button)->setStyleSheet(...);
Upvotes: 2
Reputation: 4367
With the warning that you'll have to use the preprocessor:
#define GET_BUTTON(id) ui->locker##id
The better answer:
QPushbutton *locker1;
. Don't do that.enum
, store your data in QHash<SomeEnum, bool>
, and the buttons in a QHash<SomeEnum, QPushButton *>
.bool
s and buttons is more flexible and less breakable. It also leaves out the preprocessor, which is always a good idea.Upvotes: 1