Assign to each QAction choice (on a Qmenu) a method
-
I am following this code: https://www.tutorialspoint.com/pyqt/qmenubar_qmenu_qaction_widgets.htm
The problem is that I have assigned a method to each choice of the QMenu, for instance:
Edit (1st choice int he QMenu ("up")) ---> dothis()
Copy ---> dothat()
Cut (last choice in the QMenu ("down")) ----> doCut()but when I run the code and choose "Cut" from the QMenu it runs all 3 methods...
dothis() dothat() doCut()
however I need only the
doCut()
method to run... What I miss here???
-
Hi,
Show your code so we may see what is happening,
-
Yes, the main code:
. . . bar=self.menuBar() file=bar.addMenu("Calculations") calc_1 = QAction("Calc_1", self) file.addAction(calc_1) file.triggered[QAction].connect(self.calculate_1) calc_2 = QAction("Calc_2", self) file.addAction(calc_2) file.triggered[QAction].connect(self.calculate_2) calc_3 = QAction("Calc_3", self) file.addAction(calc_3) file.triggered[QAction].connect(self.calculate_3) self.setLayout(mylayout) self.setWindowTitle("menu demo") . . . def calculate_1(self): print("Calculating 1...") def calculate_2(self): print("Calculating 2...") def calculate_3(self): print("Calculating 3...") . . .
Any idea???
-
Why are you connecting the menu three times rather than the specific action to their corresponding slot ?
-
file.triggered[QAction].connect(self.calculate_1) file.triggered[QAction].connect(self.calculate_2) file.triggered[QAction].connect(self.calculate_3)
This sets up so that any triggered action on
file
(your whole menu with all its actions) will call each/all of your slots. That is not what the code you chose to copy from did, it had onefile.triggered[QAction].connect(self.processtrigger)
Either do it that way, or more likely just connect each
QAction
to its slot. EDIT E.g. writecalc_1.triggered.connect(self.calculate_1)
instead offile.triggered[QAction].connect(self.calculate_1)
.