How to prevent right mouse click selection for a QTreeWidget?

In order to prevent selection of an item when right clicking, you can reimplement QTreeWidget::mousePressEvent() [doc.qt.nokia.com] to do nothing if it is the right mouse button which is being clicked. The example below illustrates how this can be done.

  1. #include <QtGui>
  2.  
  3. class TreeWidget : public QTreeWidget
  4. {
  5. public:
  6.         TreeWidget()
  7.         {
  8.                 setColumnCount(1);
  9.                 QList<QTreeWidgetItem *> items;
  10.                 for (int i = 0; i < 10; ++i)
  11.                         items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("item: %1").arg(i))));
  12.                 insertTopLevelItems(0, items);
  13.         }
  14.         void mousePressEvent(QMouseEvent *event)
  15.         {
  16.                 if (event->button()== Qt::RightButton)
  17.                         return;
  18.                 else
  19.                         QTreeWidget::mousePressEvent(event);
  20.         }
  21.  
  22.         void contextMenuEvent(QContextMenuEvent *event)
  23.         {
  24.                 QMenu *menu = new QMenu(this);
  25.                 menu->addAction("first");
  26.                 menu->addAction("second");
  27.                 menu->addAction("third");
  28.                 menu->exec(QCursor::pos());
  29.         }
  30. };
  31. int main(int argc, char **argv)
  32. {
  33.         QApplication app(argc, argv);
  34.         TreeWidget box;
  35.         box.show();
  36.         return app.exec();
  37. }

1 comment

December 31, 2013

Picture of zakarrrr zakarrrr

Lab Rat

Thank you very much!

Write a comment

Sorry, you must be logged in to post a comment.