0

In my code, I have a subclass for QGraphicsScene which I use to create a "worksheet view" and a subclass for QGraphicsTextItem that I use as cells of this worksheet.

What I would like to do is to override the mouseClickEvent such that when I click at a cell, all the cells that have the same plain text will be selected. To do that, I began by getting the cell at the click position. However, when I try to print the plain text, the execution is interrupted.

I have overridden the type function as described in the documentation so I don't see why this is not working.

QtApp.h

class ScheduleSheetCell : public QGraphicsTextItem
{
    public:
        ScheduleSheetCell(const QString& text);
        enum { Type = QGraphicsItem::UserType + 8 };
        int type() const override
        {
            return Type;
        }
        void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget);

};
class ScheduleScene : public QGraphicsScene 
{
    public:
        ScheduleScene();

    protected:
        virtual void mousePressEvent (QGraphicsSceneMouseEvent* mouseEvent);
};

QtApp.cpp

void ScheduleScene::mousePressEvent(QGraphicsSceneMouseEvent* mouseEvent)
{
    QGraphicsView view = ScheduleScene::views().at(0);

    qDebug() << ScheduleScene::items().at(0)->type();

    // get scene coords from the view coord
    QPointF scenePt = view.mapToScene(mouseEvent->pos().toPoint());
    
    // get the item that was clicked on
    auto QtCell = qgraphicsitem_cast <ScheduleSheetCell*>(view.itemAt(scenePt.toPoint()));

    qDebug() << QtCell->toPlainText();

}   

1 Answers1

0

Apparently the problem was that I was trying to look for the item in the view of scene. When I changed

    QGraphicsView view = ScheduleScene::views().at(0);

    qDebug() << ScheduleScene::items().at(0)->type();

    // get scene coords from the view coord
    QPointF scenePt = view.mapToScene(mouseEvent->pos().toPoint());
    

to

        QGraphicsItem* item = itemAt(mouseEvent->scenePos(), QTransform());
        ScheduleSheetCell* QtCell = qgraphicsitem_cast<ScheduleSheetCell*>(item);

as described in https://stackoverflow.com/a/26081876/14243513, the issue went away

  • 1
    Note that the 'real' bug in your original code (the one causing the crash) is that you never check the value returned by `qgraphicsitem_cast` against `nullptr`. *Always* check the value returned by runtime casts before dereferencing. – G.M. May 22 '22 at 08:25