HP Peng
HP Peng

Reputation: 325

Mac PyQt5 menubar not active until unfocusing-refocusing the app

I have problems in creating the Qt menubar using PyQt5 in Mac.

The problem I have is the menubar would show up, but won't react until I unfocus the app (by clicking the other app), then refocus the Qt app again.

Here's my environment:

OS: Sierra 10.12

Python: Python 3.6 from conda

PyQt5: conda default(v5.3.1)

Here's my code (mostly from http://zetcode.com/gui/pyqt5/menustoolbars/):

import sys

from PyQt5.QtWidgets import QMainWindow, QAction, QDesktopWidget, QApplication, qApp, QMenuBar

class Example(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.resize(800, 600)
        self.center()
        self.setWindowTitle('Menubar')

        exitAction = QAction(' &Exit', self)
        exitAction.setShortcut('Ctrl-Q')
        exitAction.setToolTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        self.show()

    def center(self):

        center_point = QDesktopWidget().availableGeometry().center()
        frame = self.frameGeometry()
        frame.moveCenter(center_point)
        self.move(frame.topLeft())


if __name__ == '__main__':

    app = QApplication(sys.argv)
    window = Example()
    sys.exit(app.exec_())

The picture below shows the menu bar is present, but it just won't respond to my click until I select other app and return to my Qt app again.

enter image description here I've searched many site and found no solution. The closest one is this (https://github.com/robotology/yarp/issues/457) but it doesn't seem to help.

Upvotes: 6

Views: 1210

Answers (1)

Daniel Alarcon
Daniel Alarcon

Reputation: 149

Run your code using pythonw rather than python3. So for example, if your file is called test-gui.py, in the command line terminal, type in:

pythonw test-gui.py

This fixed the error for me. It treats the code as an executable, so the OS isn't confused as to what is being run.

Upvotes: 6

Related Questions