user3204810
user3204810

Reputation: 391

Trouble with QTableWidget right-click event

I was able to simulate the Right-Click event by subclassing the QTableWidget:

header file:

#ifndef QRIGHCLICKTABLE_H
#define QRIGHCLICKTABLE_H

#include <QTableWidget>
#include <QMouseEvent>

class QRightClickTable : public QTableWidget
{
    Q_OBJECT

public:
    explicit QRightClickTable(QWidget *parent = 0);

private slots:
    void mousePressEvent(QMouseEvent *e);

signals:
    void rightClicked();

public slots:

};

#endif // QRIGHCLICKTABLE_H

cpp file

QRightClickTable::QRightClickTable(QWidget *parent) :
    QPushButton(parent)
{
}

void QRightClickTable::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::RightButton)
        emit rightClicked();
}

QRightClickTable *button = new QRightClickTable(this);
ui->gridLayout->addWidget(button);
connect(button, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));


void MainWindow::onRightClicked()
{
    qDebug() << "User right clicked me";
}

Now, right-click works correctly, but there are other problems with QTableWidget: all other mouse events, such as the left click to select a cell, no longer work. Can you help me?

Upvotes: 1

Views: 6225

Answers (2)

    softwareTableWidget = new QTableWidget();
    softwareTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    QObject::connect(softwareTableWidget, &QTableWidget::customContextMenuRequested, this, [this](){
        QMenu *menu = new QMenu;
        auto a = menu->addAction("Test");
        QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
            qDebug() << "Test";
            a->deleteLater();
            menu->deleteLater();
        });
        menu->exec(QCursor::pos());
        menu->clear();
    });

If you want to show context menu only at item click then add this:

if (softwareTableWidget->itemAt(softwareTableWidget->mapFromGlobal(QCursor::pos())))
        {
            QMenu *menu = new QMenu;
            auto a = menu->addAction("Test");
            QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
                qDebug() << "Test";
                a->deleteLater();
                menu->deleteLater();
            });
            menu->exec(QCursor::pos());
            menu->clear();
        }

Of course you can do whatever you want instead of showing context menu

Upvotes: 3

D Drmmr
D Drmmr

Reputation: 1243

You need to call the base class implementation in your override of mousePressEvent. Assuming you don't want the right-click event to also be handled by QTableView:

void QRightClickTable::mousePressEvent(QMouseEvent* e)
{
    if (e->button() == Qt::RightButton) {
        emit rightClicked();
    }
    else {
        QTableWidget::mousePressEvent(e);
    }
}

Upvotes: 2

Related Questions