PDA

View Full Version : QTreeWidget - no selection with mouse right click



kmilo9999
16th June 2017, 20:13
Hi,

I'm using a QTreeWidget to display a list of items. I want to avoid selecting items when the mouse right button is pressed on the widget. I tried several approaches:

1. using eventFitler:



myTreeWidget->installEventFilter(this);

bool MyClassViewsWidget::eventFilter(QObject *obj, QEvent *event)
{

if (event->type() == QEvent::ContextMenu)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);

if (mouseEvent)
{

return true;
}

}
return false;

}

but still the items got selected. Then I used a global variable that would help me keep track if the right button was pressed:


bool rightButtonPressed = false;

bool MyClassViewsWidget::eventFilter(QObject *obj, QEvent *event)
{

if (event->type() == QEvent::ContextMenu)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);

if (mouseEvent)
{

rightButtonPressed = true;
return true;
}

}
return false;

}

and then ask in the itemPressed signal if this variable is true, if it is then don't apply changes:


connect(myTreeWidget, SIGNAL(itemPressed(QTreeWidgetItem*,int)), SLOT(onItemPressed()));

void MyClassViewsWidget::onItemPressed()
{
if (!rightButtonPressed )
{
applyChanges();
}
else
{
rightButtonPressed = false;
}

}

then I realized that the itemPressed signal is being called first than eventFilter, which it won't allow me to change the state of the global variable.


2. Then I used :


connect(myTreeWidget, SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(onCustomContextMenu(const QPoint &)));


void DtObserverViewsWidget::onCustomContextMenu(const QPoint& point)
{
std::cout << "onCustomContextMenu(const QPoint& point)" << std::endl; // this was only a test
}

but again, the itemPressed signal gets called first than customContextMenuRequested.

Is there any way to control the mouse right button event to not select any item in the QTreeView?
What other approach can I try?

wysota
18th June 2017, 00:28
Try installing the event filter on the tree widget's viewport().

kmilo9999
19th June 2017, 17:17
Hi, At the end I just extended from QTreeWidget and re implement function mousePressEvent




class MyQtreeView : public QTreeWidget
{
Q_OBJECT
public:
MyQtreeView (QWidget *parent = 0);
protected:
virtual void mousePressEvent(QMouseEvent *event);
};

and in the cpp file:



void MyQtreeView ::mousePressEvent(QMouseEvent *event)
{
if (event->button() != Qt::RightButton)
{
QTreeWidget::mousePressEvent(event);
}
}