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)
        {
            close();
        }
    }
    

    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).


  • Qt Champions 2017

    Hi
    if you mean a normal context menu ?
    then something like

     ui->theview->setContextMenuPolicy(Qt::CustomContextMenu);
      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));
              menu->popup(ui->theview->viewport()->mapToGlobal(pos));
        });
    

    Hmm. maybe i misread what you try..


  • Moderators

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


  • Qt Champions 2017

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

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.