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) :
    QTableWidget(parent)
    {
    }

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

    QRightClickTable *tablewidget = new QRightClickTable(this);
    ui->gridLayout->addWidget(tablewidget);
    connect(tablewidget, 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? I know I need to call the base class implementation in your override of mousePressEvent, you could show me how?


  • Lifetime Qt Champion

    Hi,

    You need to call the base class implementation of the method if you want the original behavior plus your own.



  • Could you show me how?


  • Lifetime Qt Champion

    Please, do your homework, this is basic C++

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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.