我需要一个 checkable QAction
,除了检查模式和取消选中部分检查的选项外。这基本上已经是 QCheckBox 提供的,但不幸的是,QAction 没有提供。
作为第一次尝试,我通过实现一个自定义的QWidgetAction
.
三态文件
#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:
主文件
#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 Action。但是,与普通的 QAction 不同,TriState 在交互时不会关闭菜单。这怎么能行?
另一个问题是我的 TriState Action 的不同布局(视觉表示)。与普通的 QAction 相比,如何使它更相似?(实际上,这似乎是一个非常困难的问题。)