我有一个带有mainWindow类定义的UI.py文件(使用Qt Designer和Pyside构建)。 UI在主模块中导入。 在Ui我有一个列表框。基于鼠标左键或右键单击项目,必须执行一个过程,例如leftMouseClicked和rightMouseClicked。 谢谢你的帮助。
答案 0 :(得分:1)
您可以在QListWidget子类中定义mousePressEvent()方法来处理鼠标按下事件。获取事件参数单击的按钮并将其保存到属性。
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyListWidget(QListWidget):
def __init__(self, parent=None):
super(MyListWidget, self).__init__(parent)
self.itemClicked.connect(self.on_item_clicked)
def mousePressEvent(self, event):
self._mouse_button = event.button()
super(MyListWidget, self).mousePressEvent(event)
def on_item_clicked(self, item):
print item.text(), self._mouse_button
class Frame(QWidget):
def __init__(self, parent=None):
super(Frame, self).__init__(parent)
self.item_ctrl = items = MyListWidget(self)
self.item_ctrl.addItem("Item1")
self.item_ctrl.addItem("Item2")
box = QVBoxLayout()
box.addWidget(self.item_ctrl)
self.setLayout(box)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = Frame()
main.show()
sys.exit(app.exec_())
编辑:如果您使用QListView:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
# create table
list_data = [1,2,3,4]
lm = MyListModel(list_data, self)
lv = MyListView()
lv.setModel(lm)
lv.clicked.connect(self.item_clicked)
self.lv = lv
# layout
layout = QVBoxLayout()
layout.addWidget(lv)
self.setLayout(layout)
def item_clicked(self, index):
print "row=", index.row(), "button=", self.lv._mouse_button
class MyListView(QListView):
def mousePressEvent(self, event):
self._mouse_button = event.button()
super(MyListView, self).mousePressEvent(event)
class MyListModel(QAbstractListModel):
def __init__(self, datain, parent=None, *args):
""" datain: a list where each item is a row
"""
QAbstractListModel.__init__(self, parent, *args)
self.listdata = datain
def rowCount(self, parent=QModelIndex()):
return len(self.listdata)
def data(self, index, role):
if index.isValid() and role == Qt.DisplayRole:
return QVariant(self.listdata[index.row()])
else:
return QVariant()
if __name__ == "__main__":
main()