Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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:

    ui->tree->setContextMenuPolicy(Qt::CustomContextMenu);
    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) {
        contextMenu->exec(ui->tree->viewport()->mapToGlobal(pos));
      }
    } 
    

    But i get nothing.
    Ideas?


  • Lifetime Qt Champion

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

    rest of code looks good.

    try

     if ( true /*index.isValid() && index.row() % 2 == 0*/) {
        contextMenu->exec(ui->tree->viewport()->mapToGlobal(pos));
      }
    

    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

    @developer_61

    ok?
    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

    @developer_61

    Super.
    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()));
    menu->popup(QCursor::pos());
    menu->exec();
    }



  • @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