解决方案#1(感谢Brendan Abel)。
使用installEventFilter()
方法路由通过易于被定制eventFilter()
方法的所有lineedit事件:
self.line.installEventFilter(self)
现在所有的事件self.line
触发器要经过eventFilter
。使用有收到event
对象,我们查询现在的位置使用:
event.pos()
我们发送给leftClicked()
方法作为参数(同样的方法被称为上lineeidit的右键)。 从PyQt4.QtCore进口* 从PyQt4.QtGui进口* 进口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.line.installEventFilter(self)
self.menu=QMenu(self.line)
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.leftClicked)
self.line.cursorPositionChanged.connect(self.leftClicked)
layout=QVBoxLayout(self)
layout.addWidget(self.line)
self.setLayout(layout)
def eventFilter(self, widget, event):
print 'eventFilter', widget, event
if widget == self.line and isinstance(event, QMouseEvent) and event.buttons() & Qt.LeftButton:
self.leftClicked(event.pos())
return True
return False
def leftClicked(self, QPos):
print 'leftClicked', 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_())
溶液#2
首先QLineEdit
的最易于触发cursorPositionChanged
信号连接到的方法。 当在左击调用此方法查询与Qt的QCursor.pos()
当前鼠标光标位置:返回类似
current_mouse_cursor=QCursor.pos()
:
QtCore.QPoint(852, 595)
最后菜单移至查询鼠标光标位置并显示:
self.menu.move(current_mouse_cursor)
self.menu.show()
工作代码如下:
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)
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.rightClicked)
self.line.cursorPositionChanged.connect(self.leftClicked)
layout=QVBoxLayout(self)
layout.addWidget(self.line)
self.setLayout(layout)
def leftClicked(self, arg):
print 'leftClicked', arg, QCursor.pos()
self.menu.move(QCursor.pos())
self.menu.show()
def rightClicked(self, QPos):
print 'rightClicked', 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_())
感谢您的建议! – alphanumeric 2015-01-20 23:34:42