我需要一个可检查的QAction,它除了模式检查和未检查之外,还有部分检查的选项。这基本上已经是QCheckBox所提供的,但不幸的是,QAction并没有提供。
作为第一次尝试,我通过实现自定义QWidgetAction提出了以下方法。
TriState.h
#pragma once
#include <QWidgetAction>
#include <QCheckBox>
#include <QLabel>
#include <QFrame>
#include <QHBoxLayout>
class TriStateAction : public QWidgetAction {
Q_OBJECT
public:
TriStateAction(QWidget* parent=nullptr) : QWidgetAction(parent) {
mChkBox = new QCheckBox;
mChkBox->setTristate(true);
auto widget = new QFrame;
widget->setLayout(new QHBoxLayout);
widget->layout()->addWidget(mChkBox);
widget->layout()->addWidget(new QLabel("TriState"));
setDefaultWidget(widget);
connect(mChkBox, &QCheckBox::stateChanged, this, &QWidgetAction::changed);
}
void setCheckState(Qt::CheckState checkState) {
mChkBox->setCheckState(checkState);
}
Qt::CheckState checkState() const {
return mChkBox->checkState();
}
private:
QCheckBox* mChkBox{ nullptr };
};有了这个简单的TestRunner:
main.cpp
#include <QApplication>
#include <QMenu>
#include <QAction>
#include "TriStateAction.h"
int main(int argc, char** args) {
QApplication app(argc, args);
auto label=new QLabel("Test");
label->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
label->connect(label, &QLabel::customContextMenuRequested, [&](const QPoint& point) {
QMenu menu(label);
auto globalPoint = label->mapToGlobal(point);
auto triStateAction = new TriStateAction();
auto normalAction = new QAction("Check");
normalAction->setCheckable(true);
normalAction->setChecked(true);
menu.addAction(triStateAction);
menu.addAction(normalAction);
menu.exec(globalPoint);
});
label->show();
app.exec();
}现在,上下文菜单弹出,我可以愉快地检查、取消和部分检查我的TriState操作。但是,与普通的QAction不同,TriState在交互时不会关闭菜单。这是怎么回事?
另一个问题是我的TriState操作的不同布局(可视化表示)。与普通的QAction相比,如何使其更加相似?(实际上,这似乎是一个非常棘手的问题。)
发布于 2018-12-17 13:03:19
让操作知道它的菜单,在main中添加这一行
triStateAction->setMenu(&menu);在TriStateAction类中,添加一个插槽以捕获复选框stateChanged信号,然后从那里关闭菜单:
private slots:
void checkBoxStateChanged(int)
{
if (menu() != nullptr)
{
menu()->close();
}
}不要忘记在TriStateAction构造函数中连接插槽:
connect(mChkBox, &QCheckBox::stateChanged, this, &TriStateAction::checkBoxStateChanged);https://stackoverflow.com/questions/53812862
复制相似问题