mouseMoveEvent and mousePressEvent is not executed after deleting the table item widget on which the mouse was initially pressed

I have a QTableView (inheritor) and it has methods mouseMoveEvent, mousePressEvent, mouseReleaseEvent.

I click on the widget item inside QTableView and start to move the mouse to the left on other items (selection).

At the same time, the first widget item I clicked is deleted.

And after that, the mouseMoveEvent and mouseReleaseEvent events in QTableView stop coming until I release the mouse button. How to fix it?

class MyView : public QTableView
{
    Q_OBJECT
public:
    MyView (MyModel* pModel, QWidget* pParent);

    QSize minimumSizeHint() const override;
    QSize sizeHint() const override;

private:
    void mouseMoveEvent(QMouseEvent* pEvent) override;
    void mousePressEvent(QMouseEvent* pEvent) override;
    void mouseReleaseEvent(QMouseEvent* pEvent) override;

    QPointer<MyModel> model;
};

....

setMouseTracking(true);
setSelectionMode(QAbstractItemView::ExtendedSelection);
setSelectionBehavior(QAbstractItemView::SelectItems);

I tried to forward the button pressing event from the widget item to the view when pressed on the widget item. And also during its destruction.

I also tried to set the focus on the view at the time of the destruction of the widget item

All this did not lead to a positive result.

1

There are 1 answers

0
Cem Polat On

Instead of subclassing QTableView, subclass QTableWidget. The below code demonstrates that mouse move and mouse release events are still executed after a cell is deleted.

#include <QApplication>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QMouseEvent>
#include <QDebug>

class CustomTableWidget : public QTableWidget
{
public:
    CustomTableWidget(QWidget* parent = nullptr) : QTableWidget(parent) {}

protected:
    void mouseMoveEvent(QMouseEvent* event) override
    {
        qDebug() << "Mouse Move Event";
        QTableWidget::mouseMoveEvent(event);
    }

    void mouseReleaseEvent(QMouseEvent* event) override
    {
        qDebug() << "Mouse Release Event";
        QTableWidget::mouseReleaseEvent(event);
    }
};

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    CustomTableWidget table;
    table.setColumnCount(5);
    table.setRowCount(5);

    for (int row = 0; row < 5; ++row)
    {
        for (int col = 0; col < 5; ++col)
        {
            QTableWidgetItem* item = new QTableWidgetItem(QString("Item %1-%2").arg(row).arg(col));
            table.setItem(row, col, item);
        }
    }

    table.show();

    // Simulate widget item deletion (e.g., when a cell is clicked)
    QTableWidgetItem* itemToDelete = table.item(1, 1);
    if (itemToDelete)
    {
        delete itemToDelete;
    }

    return app.exec();
}