Qt World Summit: Submit your Presentation

How to use right click instead of left click for the on_listView_clicked slot from QListView?

  • Hi. I have a QListView widget in which, when I click on one item from it, would show a context menu. I managed to do so, except it works for the left click only. I tried to find a way to make it work for the right click, but I'm a bit confused. I found out information regarding using the mousePressEvent method, except I'm not sure if it's done correctly. As I've seen in many examples, overriding the mousePressEvent method should work, but in my case it doesn't do anything.

    Here is the mousePressEvent as I have it in mainwindow.cpp:

    void MainWindow::mousePressEvent(QMouseEvent *e)
        if(e->button() == Qt::RightButton)

    I also read about using a subclass, but it seemed a bit cumbersome to me, given the fact that I've seen other ways to do it, like the one I'm trying right now (not very successfully though).

  • Lifetime Qt Champion

    if you mean a normal context menu ?
    then something like

      connect(ui->theview, &QListView::customContextMenuRequested, [this](QPoint pos){
              QModelIndex index=ui->lwShapes->indexAt(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));

    Hmm. maybe i misread what you try..

  • @DoubleC122

    Did you checkout the mousePressEvents of QListView?

    You would need to inhgerit from QListView and overwrite one of these events.

  • @mrjj Oh, I already have the context menu working, my issue is that I want it to pop when I use right click, not left click as it is by default. That is the reason why I was trying to use that mousePressEvent.

  • Lifetime Qt Champion

    ok, but customContextMenuRequested pops on right click pr default so
    i was wondering if that was easier ?

  • @mrjj I see. I'll try with that.

  • @mrjj Alright that seems to do the job quite fine. Thank you very much for your time.

Log in to reply