elgolondrino
elgolondrino

Reputation: 665

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.

Upvotes: 1

Views: 3465

Answers (2)

Blob
Blob

Reputation: 146

In my case, I started trying to catch mouse events when a user right-clicked on a line in the QListView, but they never came through. However, all I really wanted to do was popup a context menu, and it turns out the contextMenuEvent did get through! So I didn't have to subclass QListView, just added a contextMenuEvent() to my widget that contained the QListView.

This was Qt3, so your mileage will most definitely differ.

Upvotes: 0

Jablonski
Jablonski

Reputation: 18504

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
}

Upvotes: 2

Related Questions