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();
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…