I have a QToolButton button1
with a popup QMenu menu
. I add another QToolButton button2
into the menu
. I have already defined the ObjectName. But the auto connect only works for button1
, not button2
.
For the main window
QToolButton *button1 = new QToolButton();
button1->setObjectName("action1");
button1->setText("Save");
button1->setPopupMode(QToolButton::MenuButtonPopup);
QToolButton *button2 = new QToolButton();
button2->setObjectName("action2");
button2->setText("Save11");
QMenu *pMenu = new QMenu("Title");
QWidgetAction *ptoolButtonAction = new QWidgetAction(pMenu);
ptoolButtonAction->setDefaultWidget(button2);
pMenu->addAction(ptoolButtonAction);
button1 ->setMenu(pMenu);
QMetaObject::connectSlotsByName(this);
For the public slots part
void MyClass::on_action1_clicked()
{
qDebug() << "action1 is clicked";
}
void MyClass::on_action2_clicked()
{
qDebug() << "action2 is clicked";
}
In the terminal, when I click button1
"Save", it shows the "action1 is clicked."
But when I click button2
"Save1", it shows nothing.
Update: Solve the issue by fixing
QMenu *pMenu = new QMenu("Title", this);
also, the objectName should by unique, or the auto connect will fail for others.
Your QObject hierarchy is flawed because you do not set an owner for the QToolButtons and the QMenu. connectSlotsByName
walks the hierarchy to find objects and signals matching slots.