0
votes

I have a QTreeWidget where I want to disable right click on the item. Currently I am using itemClicked signal to detect clicks on children of the treeWidget, but I only want to do something when the user left clicks an item and do nothing on right click. Both left and right clicks are getting detected right now and I am not able to differentiate between the two. Thanks in advance!

3

3 Answers

4
votes

You can reimplement the treewidget's mouse release event:

class TreeWidget(QtGui.QTreeWidget):    
    def mouseReleaseEvent(self, event):
        if event.button() != QtCore.Qt.RightButton:
            super(TreeWidget, self).mouseReleaseEvent(event)

or install an event-filter on the treewidget's viewport:

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        ...
        self.tree = QtGui.QTreeWidget(self)
        self.tree.viewport().installEventFilter(self)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseButtonRelease and
            event.button() == QtCore.Qt.RightButton and
            source is self.tree.viewport()):
            return True
        return super(Window, self).eventFilter(source, event)
1
votes

You can override the MouseEvent:

void MyTreeWidget::mousePressEvent ( QMouseEvent * event )
{
   event->accept();
}

To preserve the usual behaviour of the Widget you have to call the base class for all Buttons you want to work.

void MyTreeWidget::mousePressEvent ( QMouseEvent * event )
{
   if(event->button() == Qt::RightButton)
       event->accept(); // accept event and do nothing
   else:
       QTreeView::mousePressEvent(event)
}

EDIT:

Have just noticed that you are working with Python: the mechanics are the same so the above Example should work if translated to Python.

0
votes

If I understad you correctly you want to disable selection .
I'm not familiar to PyQT but in C++ you should write code like this:

yourtreeView->setSelectionMode(QAbstractItemView::NoSelection);

In this case items would not get selected but you still will see focus rectangle around them. To fix this you can set your widget to not accept focus by calling:

yourtreeView->setFocusPolicy(Qt::NoFocus);