Create context menu when right-click on header of QTreeWidget
-
Hi,
I'm trying to write a code that shows me context menu when I press right-click on header of QTreeWidget but I only could do that for non-header area of that widget.
I use the code in mainwindow.cpp (here of course part of this file):
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); ui->treeWidget_seismic->setColumnCount(1); /* Context menu*/ connect(ui->treeWidget_seismic, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotCustomMenuRequested(QPoint))); } /* Context menu*/ void MainWindow::slotCustomMenuRequested(QPoint pos) { QModelIndex index = ui->treeWidget_seismic->indexAt(pos); QTreeWidgetItem* item = ui->treeWidget_seismic->currentItem(); menu = new QMenu(this); QAction *myAction = menu->addAction("Action 1"); menu->popup(ui->treeWidget_seismic->viewport()->mapToGlobal(pos)); connect(myAction, SIGNAL(triggered()), this, SLOT(slotAddH5File())); } void MainWindow::slotAddH5File() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Project"), QDir::homePath(), tr("Project file (*.prj)")); }
-
Hi
Its not Treewidget but a QHeaderView (up there)So its
auto widget = ui->treeWidget->header(); widget->setContextMenuPolicy(Qt::CustomContextMenu); connect(widget,&QTreeWidget::customContextMenuRequested,this,&MainWindow::slotCustomMenuRequested); // use new syntax for more joy void MainWindow::slotCustomMenuRequested(QPoint pos) { QMenu *menu = new QMenu(this); menu->addAction(new QAction("Action 1", this)); menu->addAction(new QAction("Action 2", this)); menu->addAction(new QAction("Action 3", this)); menu->popup(ui->treeWidget->header()->mapToGlobal(pos)); }
-
Hi
The default context menu is only for right-click, but its quite easy to make your own subclass of QHeaderView
and overwrite mousePress/dbclick and use show menu as you want.
Or emit a new signal so you can respond in another widget and show different menus easy/pr use case. -
@Please_Help_me_D said in Create context menu when right-click on header of QTreeWidget:
@mrjj Thank you!
Is there a way of control wether to invoke context menu after right-click or double click (or left click)?Context menu should only be displayed on right click. Otherwise your app will confuse your users ;)
Right click is simply the convention.
Regards