首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TriState QAction in QMenu

TriState QAction in QMenu
EN

Stack Overflow用户
提问于 2018-12-17 10:03:06
回答 1查看 474关注 0票数 1

我需要一个可检查的QAction,它除了模式检查和未检查之外,还有部分检查的选项。这基本上已经是QCheckBox所提供的,但不幸的是,QAction并没有提供。

作为第一次尝试,我通过实现自定义QWidgetAction提出了以下方法。

TriState.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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相比,如何使其更加相似?(实际上,这似乎是一个非常棘手的问题。)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-17 13:03:19

让操作知道它的菜单,在main中添加这一行

代码语言:javascript
复制
triStateAction->setMenu(&menu);

TriStateAction类中,添加一个插槽以捕获复选框stateChanged信号,然后从那里关闭菜单:

代码语言:javascript
复制
private slots:
    void checkBoxStateChanged(int)
    {
        if (menu() != nullptr)
        {
            menu()->close();
        }
    }

不要忘记在TriStateAction构造函数中连接插槽:

代码语言:javascript
复制
connect(mChkBox, &QCheckBox::stateChanged, this, &TriStateAction::checkBoxStateChanged);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53812862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档