[QUOTE=panupat;27537]This should give you the row the cursor is positioning over. -1 if the cursor is on empty space.
from PySide import QtGui, QtCore
class MyList(QtGui.QListView):
def __init__(self, *args, **kwargs):
super(MyList, self).__init__(*args, **kwargs)
def mousePressEvent(self, event):
if event.type() == QtCore.QEvent.MouseButtonPress:
pos = self.mapFromGlobal(QtGui.QCursor.pos())
row = self.indexAt(pos).row()
if event.button() == QtCore.Qt.RightButton:
print "Right clicked on row %s" % row
else:
print "Left clicked on row %s" % row
ML = MyList()
ML.show()
ML.raise_()
model = QtGui.QStandardItemModel()
model.appendRow(QtGui.QStandardItem('adad'))
model.appendRow(QtGui.QStandardItem('12354'))
ML.setModel(model)
[/QUOTE]
Thank you panupat, I already found the solution but it’s good to have more than 1 solution for other people that will come accross this thread. Here is how I managed to get the right result.
First I extended the QtGui.QListView class and reimplemented mousePressedEvent and mouseReleasedEvent like this:
from PySide import QtGui, QtCore
class QListView(QtGui.QListView):
def __init__(self):
super(QListView, self).__init__()
def mousePressEvent(self, event):
if event.type() == QtCore.QEvent.MouseButtonPress:
if event.button() == QtCore.Qt.LeftButton:
super(QListView, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
if event.type() == QtCore.QEvent.MouseButtonRelease:
if event.button() == QtCore.Qt.LeftButton:
super(QListView, self).mouseReleaseEvent(event)
And then in the class I named QSingleListView where I extend QtGui.QWidget I did this:
class QSingleListView(QtGui.QWidget):
def __init__(self):
super(QSingleListView, self).__init__()
self.model = None
self.initUI()
def initUI(self):
self.layout = QtGui.QVBoxLayout()
self.list = QListView() # This is the QListView class I created (mentioned above)
self.list.clicked.connect(self.clickedConnect)
self.layout.addWidget(self.list)
self.setLayout(self.layout)
def clickedConnect(self, model):
pass
Because of the overriden methods in QListView, this signal only triggers on left click (so no need to check if item was clicked or not because clicked signal only occurs on clicked items already)
So the final thought would be:
- If you wish to archieve the result only with mouse events, use panupat’s solution
- If you wish to achieve the result using connect signal, use my solution (thank you rgkovach123)