C++ Qt可检查QActions
右键单击菜单中有两个QAction。我试图检查一个动作,并在旁边打勾。如果我再次选择了正数,它会将程序返回到默认模式并删除勾号。如果在“正”之后选中“负”,则勾号应移到“负”。我修改了类似的问题,但我想不出来。我将感谢你的帮助C++ Qt可检查QActions,c++,qt,qaction,C++,Qt,Qaction,右键单击菜单中有两个QAction。我试图检查一个动作,并在旁边打勾。如果我再次选择了正数,它会将程序返回到默认模式并删除勾号。如果在“正”之后选中“负”,则勾号应移到“负”。我修改了类似的问题,但我想不出来。我将感谢你的帮助 void MainInterfaceWindow::ShowContextMenu(const QPoint &pos) { QMenu contextMenu(tr("Context menu"), this);
void MainInterfaceWindow::ShowContextMenu(const QPoint &pos)
{
QMenu contextMenu(tr("Context menu"), this);
QAction action1("Positive", this);
QAction action2("Negative", this);
contextMenu.addAction(&action1);
contextMenu.addAction(&action2);
connect(&action1, SIGNAL(triggered()), this, SLOT(positiveSlope()));
connect(&action2, SIGNAL(triggered()), this, SLOT(negativeSlope()));
m_mouseLocation=pos;
contextMenu.exec(mapToGlobal(pos));
}
void MainInterfaceWindow::positiveSlope()
{
ui->openGLWidget->m_positive_slope=true;
ui->openGLWidget->m_negative_slope=false;
}
void MainInterfaceWindow::negativeSlope()
{
ui->openGLWidget->m_negative_slope=true;
ui->openGLWidget->m_positive_slope=false;
}
你必须照你说的去做:取消选中其他动作。由于操作特定于给定的上下文菜单,因此您应该捕获它们。IIRC,每次单击这些操作时,它们都会自动选中和取消选中,因此,在没有任何附加代码的情况下,这些操作应该已经发生了 操作必须是可检查的:默认情况下它们不是 最好不要重新进入事件循环,即不要在每个线程(包括主线程,其中事件循环由
QCoreApplication::exec
启动)的根事件循环之外的任何位置使用exec
方法
在下面的代码中,连接通常在两个对象之间进行,因此如果源对象或目标对象被销毁,则函子将被销毁-通过构造确保函子在任何一个悬空时都无法访问操作指针。此外,由于上下文菜单请求处理程序函子使用m_mouseLocation
,因此该字段必须位于m_contextMenu
之前,以通过构造确保函子在成员被破坏后不会访问该成员
class MainInterfaceWindow : public ... {
QPoint m_mouseLocation; // must be before m_contextMenu
QMenu m_contextMenu{this};
...
void setupContextMenu();
};
MainInterfaceWindow::MainInterfaceWindow(QWidget *parent) :
BaseClass(..., parent)
{
setupContextMenu();
...
}
void MainInterfaceWindow::setupContextMenu()
{
m_contextMenu.setTitle(tr("Context menu");
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, &m_contextMenu, [=](const QPoint &pos){
m_mouseLocation = pos;
contextMenu.popup(mapToGlobal(pos));
});
auto *posAction = new QAction(tr("Positive"));
auto *negAction = new QAction(tr("Negative"));
for (auto *action : {posAction, negAction}) {
action->setCheckable(true);
m_contextMenu.addAction(action);
}
connect(posAction, &QAction::triggered, negAction, [=]{
negAction->setChecked(false);
ui->openGLWidget->m_positive_slope = posAction->checked();
ui->openGLWidget->m_negative_slope = negAction->checked();
});
connect(negAction, &QAction::triggered, posAction, [=]{
posAction->setChecked(false);
ui->openGLWidget->m_positive_slope = posAction->checked();
ui->openGLWidget->m_negative_slope = negAction->checked();
});
}
非常感谢你的努力!它工作得很好:)