The QMenu
shows up on a QLineEdit
right-click.
Question: How to modify this code to show the menu on a left-click as well?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
def actionFunct(self, argBool):
print 'actionFunct()', argBool
def buildGUI(self):
self.line=QLineEdit(self)
self.line.setText('My Line Edit')
self.menu=QMenu(self.line)
self.line.installEventFilter(self)
self.menu.installEventFilter(self)
for i in range(3):
actn=QAction('Action 0%s'%i, self.menu, checkable=True)
actn.triggered.connect(self.actionFunct)
self.menu.addAction(actn)
self.line.setContextMenuPolicy(Qt.CustomContextMenu)
self.line.connect(self.line, SIGNAL("customContextMenuRequested(QPoint)" ), self.lineClicked)
layout=QVBoxLayout(self)
layout.addWidget(self.line)
self.setLayout(layout)
def lineClicked(self, QPos):
print 'lineClicked', QPos
parentPosition = self.line.mapToGlobal(QPoint(0, 0))
menuPosition = parentPosition + QPos
self.menu.move(menuPosition)
self.menu.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.buildGUI()
w.show()
sys.exit(app.exec_())
You need to define an eventFilter method on your Window class to filter/handle the event.
def eventFilter(self, obj, event):
if obj == self.line and isinstance(event, QMouseEvent) and event.buttons() & Qt.LeftButton:
self.lineClicked(event.pos())
return True
return False