Search code examples
qtqt4qt5qt4.8

Handle mouse events in QListView


I've Dialog that shows folders (in treeView) and files (in listView) respectively. In listView doubleClick signal is handled by a slot that Qt created while I used Designer with aproppriate slot to be implemented. The problem is that I'm not able to handle RIGHT MOUSE click. Is there a solution?

P.S. I've googled for a while to solve this problem, it seems that inheriting QListView and overriding solve the problem. But in my case I've already populated Qt's standart QListView using Designer.


Solution

  • In this case you can use event filter:

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
    
        if (obj == ui->listView->viewport() && event->type() == QEvent::MouseButtonDblClick)
        {
            QMouseEvent *ev = static_cast<QMouseEvent *>(event);
            if (ev->buttons() & Qt::RightButton)
            {
                qDebug()<< "double clicked" << ev->pos();
                qDebug()<<  ui->listView->indexAt(ev->pos()).data();
            }
        }
        return QObject::eventFilter(obj, event);
    }
    

    To use eventFilter you should also:

    protected:
        bool eventFilter(QObject *obj, QEvent *event);//in header
    

    and

    qApp->installEventFilter(this);//in constructor
    

    Possible addition to your problem. If you want do different things when user clicks left or right mouse buttons you should handle lest and right clicks in filter, without doubleClick signal (because it emits signal in both cases) and your code can be something like:

    QMouseEvent *ev = static_cast<QMouseEvent *>(event);
    if (ev->buttons() & Qt::RightButton)
    {
        qDebug()<< "RightButton double clicked";
        //do something
    }
    if (ev->buttons() & Qt::LeftButton)
    {
        qDebug()<< "LeftButton double clicked";
        //do something
    }