So every single QComboBox tutorial I could find was using the exact same code and wasn't teaching how to make an action for each option. Can someone recommend me or provide some kind of tutorial for how to make something happen when a selection gets selected or highlighted? (Preferably both) Also, please don't flag this question, I need to learn from experience and I can't find anything on the web on actions with the QComboBox.
It sounds like you want to link items in a QComboBox to a QAction? When adding items to a QComboBox you can link custom user data to your item in the form of a QVariant (see QComboBox::addItem). You can then access this user data by calling QComboBox::itemData.
In your case you can set the user data of each ComboBox item to be a pointer to a QAction, which can then be accessed via QComboBox::itemData
For example:
class boxTest : public QObject
{
Q_OBJECT
public:
QAction * firstAction;
QAction * secondAction;
QComboBox *box;
boxTest();
protected slots:
void boxCurrentIndexChanged(int);
};
boxTest::boxTest()
{
firstAction = new QAction(this);
firstAction->setText("first action");
secondAction = new QAction(this);
secondAction->setText("second action");
box = new QComboBox(this);
box->addItem(firstAction->text(), QVariant::fromValue(firstAction)); //add actions
box->addItem(secondAction->text(), QVariant::fromValue(secondAction));
connect(box, SIGNAL(currentIndexChanged(int)), this, boxCurrentIndexChanged(int)));
}
void boxTest::boxCurrentIndexChanged(int index)
{
QAction * selectedAction = box->itemData(index, Qt::UserRole).value<QAction *>();
if (selectedAction)
{
selectedAction->trigger(); //do stuff with your action
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With