PDA

View Full Version : Programmatically click second item on QPushButton that has a QMenu



dennisvz
26th June 2019, 13:44
I put a three-option menu (using QMenu add.Action) on a QPushButton (ExpensesChtBtn). In other words, when the button is manually clicked, three options appear. Is it possible to programmatically "click" the second option?

To click the button, I'm pretty sure that the following is correct:



self.chartsWindow.ui.ExpensesChtBtn.clicked.emit()


How do I modify this code to effectively click the second menu item on that button -- let's say the second menu item is labeled "piechart"?
thanks

Ginsengelf
26th June 2019, 14:24
Hi, you can use QAction's trigger() method. This will not execute an animated click, but it will emit the triggered signal of the QAction.

Ginsengelf

dennisvz
26th June 2019, 14:27
How would I modify my code to trigger() the "piechart" menu item?

d_stranz
26th June 2019, 17:53
To click the button, I'm pretty sure that the following is correct:

Actually, you probably want to simply call the QPushButton::click() slot. The internal code will ensure that the right signals get emitted and the button changes state as needed.

It isn't clear what you want to happen when the button is clicked. If the user clicks the button, do you want the menu to appear and let the user choose one of the three options? If you want to programmatically choose one of the options instead, then you don't need to bother with simulating a click at all - simply call the QAction::trigger() slot as Ginsengelf suggested.

As to how, your program must be executing some code where you have programmatically decided that's what you want to do. Just call it there. You can always retrieve the list of QAction instances you have added to your button using QWidget::actions(). Use QList::at() or QList::operator[]() to retrieve the pointer to to the action at the index you want.