Pat C
Pat C

Reputation: 418

How can I detect middle clicks on PyQt QTreeWidget?

The itemClicked/itemDoubleClicked signals don't appear to distinguish between left and middle mouse clicks. I want to do different things depending on the which was clicked. It appears that clicking happens on release so app.mouseButtons() reports NoButtons by the time my itemClicked() is actually called.

While I haven't tried it yet, I'm assuming I could do some main app mouse test to store the state globally, then read it from my itemClicked(), but this feels really convoluted and hacky, is there a better way I can't find?

[UPDATED] As suggested, I overrode the tree's mouse event. I also didn't want to bother subclassing QTreeWidget just for this, so for completeness's sake, here is what I did:

setattr(self.tree, 'middleMouse', False)

def mousePressEvent(self, event):
    self.middleMouse = event.button() == QtCore.Qt.MidButton
    return QtGui.QTreeWidget.mousePressEvent(self, event)

self.tree.mousePressEvent = types.MethodType(mousePressEvent, self.tree)

def itemClicked(item):
    if self.tree.middleMouse:
        <do something>
    else:
        <do another thing>

self.tree.itemClicked.connect(itemClicked)

Python is the best.

Upvotes: 0

Views: 1171

Answers (1)

FLCcrakers
FLCcrakers

Reputation: 445

The only way I see is to reimplement the mouseDoubleClickEvent(QMouseEvent * event) of the QTreeWidget and to change the behaviour depending on the button which trigger the event.

What you can do it with something like:

yourQtTreeView.mouseDoubleClickEvent = self.mymouseDoubleClickEvent

def mymouseDoubleClickEvent(event):
    #your code capturing the event

I haven't tested this, but I think it's the direction.

Upvotes: 1

Related Questions