CubicDE
CubicDE

Reputation: 23

Can a QMenu be used like a Button

I searched some time for this topic but i didnt find anything

I want to use a QMenu like a Button but it has no clicked event and the triggered Event doesent seem to work either.

I tried it like that:

self.ui.menuInfo.triggered.connect(self.MenuInfoClicked)

but nothing happens when i click the Menu.

I have a MainWindow with a QMenuBar and multiple QMenus in it. But I dont want to open a submenu with QActions i just want to use it as a Button to open a info popup

As for my code, i compiled the ui with pyuic5 and then i imported the UI like that

from PyQt5 import QtWidgets
import sys
import MainWindow

class GUI(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = MainWindow.Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.menuInfo.triggered.connect(self.MenuInfoClicked)

    def MenuInfoClicked(self):
        print("test!")


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = GUI()
    mainWindow.show()
    sys.exit(app.exec_())

The UI: enter image description here

Compiled UI Code (MainWindow.py):

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(634, 415)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 634, 21))
        self.menubar.setObjectName("menubar")
        self.menuInfo = QtWidgets.QMenu(self.menubar)
        self.menuInfo.setObjectName("menuInfo")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuInfo.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.menuInfo.setTitle(_translate("MainWindow", "Info"))

Upvotes: 1

Views: 648

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

The triggered signal is triggered when a QAction is pressed but in this case there are none. Instead you should use the aboutToShow signal:

self.ui.menuInfo.aboutToShow.connect(self.MenuInfoClicked)

Upvotes: 3

Related Questions