在Qt5中,你可以使用QAction :: triggered()信号来检测操作被点击时。当操作的快捷键被激活时,或者当操作从菜单或工具栏中被选择时,将发出此信号。可以将信号连接到插槽函数,然后可以使用 QObject::sender() 函数获取发出信号的QAction的指针,然后可以使用 QAction::text() 函数获取action的文本。
connect(action, &QAction::triggered, this, [this](){
QAction* action = qobject_cast<QAction*>(sender());
QMessageBox::information(this, "Info", action->text() + " 被点击.");
});
另外,你还可以使用QAction :: setData()为操作设置特定值并在以后使用。如果有多个具有相同名称的操作,这很有用。
action->setData(QVariant(1));
connect(action, &QAction::triggered, this, [this](){
QAction* action = qobject_cast<QAction*>(sender());
int data = action->data().toInt();
QMessageBox::information(this, "Info", QString::number(data) + " 被点击.");
});