alphanumeric
alphanumeric

Reputation: 19329

Why QMenu reappears after function is called

This example creates a single QListWidget with its items right-click enabled. Right-click brings up QMenu. Choosing a menu opens a OS File Browser in a current user's home directory. After a File Browser is closed QMenu re-appears which is very annoying. How to avoid this undesirable behavior?

enter image description here

import sys, subprocess
from os.path import expanduser
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.listWidget = QtGui.QListWidget()
        self.listWidget.addItems(('One','Two','Three','Four','Five'))
        self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.listWidget.connect(self.listWidget,QtCore.SIGNAL('customContextMenuRequested(QPoint)'),self.showMenu)

        self.menu=QtGui.QMenu()
        menuItem=self.menu.addAction('Open Folder')        
        self.connect(menuItem,QtCore.SIGNAL('triggered()'),self.openFolder) 
        layout.addWidget(self.listWidget)

    def showMenu(self, QPos):
        parentPosition=self.listWidget.mapToGlobal(QtCore.QPoint(0, 0))        
        menuPosition=parentPosition+QPos
        self.menu.move(menuPosition)
        self.menu.show() 

    def openFolder(self):
        if sys.platform.startswith('darwin'):
            subprocess.call(['open', '-R',expanduser('~')])
        if sys.platform.startswith('win'):
            subprocess.call(['explorer','"%s"'%expanduser('~')])

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

Upvotes: 0

Views: 164

Answers (1)

Bo Milanovich
Bo Milanovich

Reputation: 8203

Two ideas come to my mind:

  1. Try adding self as a constructor parameter when defining QMenu(), passing your QWidget as a parent.

  2. Call self.menu.hide() in the openFolder() method.

  3. Tip: instead of using subprocess to open up explorer, there's an arguably better, cross platform solution in Qt called QDesktopServices - see http://pyqt.sourceforge.net/Docs/PyQt4/qdesktopservices.html

Upvotes: 1

Related Questions