通过子类化QTableWidget,我能够模拟Right-Click事件:

头文件:

#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文件
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";
}

现在,右键单击可以正常工作,但是QTableWidget仍然存在其他问题:所有其他鼠标事件(例如,单击鼠标左键选择一个单元格)将不再起作用。
你能帮助我吗?

最佳答案

您需要在mousePressEvent的覆盖中调用基类实现。假设您不希望QTableView也处理右键单击事件:

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

10-08 07:55