Catch which mousebutton is pressed on item

2019-08-29 12:44发布

问题:

I have a UI.py file with the mainWindow class definition (build with Qt Designer and Pyside). The UI is imported in the main module. In the Ui I have a listbox. Based on the left or right mouse clicked on an item a procedure must be executed, e.g leftMouseClicked and rightMouseClicked. Thanks for your help.

回答1:

you can define a mousePressEvent() method in your QListWidget subclass to handle mouse press event. Get which button is clicked by the event parameter and save it to an attribute.

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_())

Edit: If you use 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()