所以我能找到的每一个QComboBox教程都是使用完全相同的代码,而不是教你如何为每个选项做一个动作。有没有人可以推荐我,或者提供一些教程,告诉我如何在选择或高亮显示时实现某些功能?(最好两者都有)另外,请不要标记这个问题,我需要从经验中学习,我在网上找不到任何关于QComboBox操作的东西。
发布于 2016-08-06 00:10:13
听起来您想要将QComboBox中的项目链接到QAction?将项目添加到QComboBox时,您可以以QVariant (see QComboBox::addItem)的形式将自定义用户数据链接到您的项目。然后,您可以通过调用QComboBox::itemData来访问此用户数据。
在本例中,您可以将每个ComboBox项的用户数据设置为指向QAction的指针,然后可以通过QComboBox::itemData访问该指针
例如:
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
}
}发布于 2016-07-22 13:23:54
当用户更改当前项目并突出显示项目时,QComboBox会发出信号currentIndexChanged(int index)和highlighted(int index)。这些信号的参数是高亮/当前项索引。
要对项目更改/高亮显示进行定义和操作,您可以使用userData -将QVariant变量添加到每个项目(参见void QComboBox::addItem(const QString &text, const QVariant &userData = QVariant())),然后使用QVariant QComboBox::itemData(int index, int role = Qt::UserRole)在相应的插槽中获取此变量,分析此数据并处理任何操作。
https://stackoverflow.com/questions/38516790
复制相似问题