Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

c++ - Access to QCheckBox from QWidgetAction

Please consider the bellow codes:

QMenu* menu_ = new QMenu(this);
QWidgetAction *checkableAction = new QWidgetAction(menu_);

QCheckBox* checkBox1 = new QCheckBox("Sample1", menu_);
QCheckBox* checkBox2 = new QCheckBox("Sample2", menu_);

checkableAction->setDefaultWidget(checkBox1);
checkableAction->setDefaultWidget(checkBox2);

connect(checkableAction, &QWidgetAction::toggled, this, &MenuPushButton::onRec_triggered);

How can I access to QCheckBox features from QWidgetAction in onRec_triggered slot. I try the bellow codes but it does not works for me.

void MenuPushButton::onRec_triggered()
{
    for(QAction* action : menu_->actions())
        if(dynamic_cast<QCheckBox*>(action)->isChecked())
            qDebug()<<dynamic_cast<QCheckBox*>(action)->text();
}
question from:https://stackoverflow.com/questions/65600150/access-to-qcheckbox-from-qwidgetaction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This answer is based on code snippets provided by question. However i am not sure if the intention was to use "checkable" feature of base class QAction.

If you want to use the checkbox you set as QWidgetAction default widget to trigger your slot then you have to use connect(checkBox2, &QCheckBox::toggled, this, &MenuPushButton::onRec_triggered);. You can remove checkBox1 as it gets overridden by checkBox2 as default widget. In your slot you have to use a two step dynamic_cast. First dynamic_cast to check if action is of type QWidgetAction * and if that matches call defaultWidget() and try to dynamic_cast result to QCheckBox *. If that matches too then call text() method. Always check result of dynamic_cast before you call any method to avoid accessing a nullptr.

void MenuPushButton::onRec_triggered()
{
    for(QAction* action : menu_->actions()) {
        QWidgetAction *wa = dynamic_cast<QWidgetAction*>(action);
        if (wa) {
            QCheckBox *cb = dynamic_cast<QCheckBox*>(wa->defaultWidget());
            if (cb) {
                qDebug() << cb->text();
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...