简体   繁体   中英

Qt/PyQt: How do I use a QMenu as a permanent widget?

I would like to use a QMenu as a permanent widget in the gui. (I like its appearance and layout, and the fact that as soon as I hover over it, the requisite menu pops up, no clicking needed. It would be a pain in the neck to try and emulate it with a custom widget.) I have tried adding it to a parent widget's layout, but after the first time it is used, it disappears. How would I go about keeping it there?

I can't find any option in QMenu that would disable auto-hide, so simplest way would be a subclass that overrides hideEvent . hideEvent is fired just before hide() completes. That means you can't intercept/ignore hide() but you can re-show it:

class PermanentMenu(QtGui.QMenu):
    def hideEvent(self, event):
        self.show()

Just make your top-level menu from PermanentMenu and it should be fine.

A simple example using it:

import sys
from PyQt4 import QtGui

class PermanentMenu(QtGui.QMenu):
    def hideEvent(self, event):
        self.show()


class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.menu = PermanentMenu()

        self.menu.addAction('one')
        self.menu.addAction('two')

        self.submenu = self.menu.addMenu('submenu')
        self.submenu.addAction('sub one')
        self.submenu.addAction('sub two')

        self.submenu2 = self.menu.addMenu('submenu 2')
        self.submenu2.addAction('sub 2 one')
        self.submenu2.addAction('sub 2 two')

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.menu)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM