Important: Please read the Qt Code of Conduct -

Contextmenu in QTreeView

  • Hello !
    I want use a context menu in the QTreeView. So if i'm going to rightlick an element in the Tree i want to chose between actions.
    I tried following:

    connect(ui->tree, SIGNAL(customContextMenuRequested(const QPoint&)), SLOT(showContextMenu(const QPoint&))); 
    void MainWindow::showContextMenu(const QPoint& pos)
      auto contextMenu = new QMenu(ui->tree);
      contextMenu->addAction("Uninstall TA", this, SLOT(uninstallAppletClickedSlot()));
      QModelIndex index = ui->tree->indexAt(pos);
      if (index.isValid() && index.row() % 2 == 0) {

    But i get nothing.

  • Lifetime Qt Champion

    well its either index that is not valid or (index.row() % 2 == 0) is not true

    rest of code looks good.


     if ( true /*index.isValid() && index.row() % 2 == 0*/) {

    and see if it pops.

    also. you create a new menu each time. You could move it as a member to avoid this.

  • @mrjj i tried the debugger, i don't even get into the function.

  • Lifetime Qt Champion


    Did you check that connect returns true ?

  • @mrjj right problem solved. I got true now. Problem was with the syntax. Thank You.

  • Lifetime Qt Champion


    Can you tell what it was for me as i didnt spot it :(

  • Hi,
    First enable custom context menu by using below code and connect the slot

    ui->treeView->setContextMenuPolicy( Qt::CustomContextMenu );
    connect(ui->treeView, SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(ShowContextMenuMessage(QPoint)));

    In slot create menu and pop up the menu in mouse position like this

    void Mainwindow::ShowContextMenuMessage(QPoint p)
    QMenu *menu = new QMenu("menu",ui->treeView_Messages);
    menu->addAction(QIcon(":/new/prefix1/Icons/add.ico"),"Add Tag",this,SLOT(addNewTag()));

  • @mrjj sure :). I spot that there is another syntax for the connect function with &.
    i use:

    connect(ui->tree,&QWidget::customContextMenuRequested ,this, &MainWindow::showContextMenu);

    and it works fine.
    I think you would spot it easy if you would see the whole code.

    @ManjunathXI thank you already solved!

Log in to reply