QTableWidget右键单击事件有问题

时间:2014-05-31 22:11:25

标签: c++ qt class mouseevent

我能够通过继承QTableWidget来模拟右键单击事件:

头文件:

#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还有其他问题:所有其他鼠标事件,例如左键单击以选择单元格,不再有效。 你能救我吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

当然,你可以做任何你想做的事情,而不是显示上下文菜单