Important: Please read the Qt Code of Conduct -

Qt Application crashing when using pointers to class instance

  • Hey all,
    I'm coding my first application in Qt with C++. When I am using pointers to point to instances of a class my Qt application crashes. Can you help me out? This might more of a C++ than a Qt problem, I don’t know.

    The point of the program is to create three rectangles with different constructors and have them show up on screen at one point. Later on I want to add QLineEdits, so that the user can enter his own values for width, height, x position, y position, etc.

    I have two header files, main.h and widget.h.

    Now, whenever I start the application to paint the rectangle using the pointer to the instance of said rectangle it crashes. Is using pointers the way to go here? I wanted to avoid declaring the class instance globally.

  • You never assign a value to

    cRechteck *nextptr = 0;

    Since it is alway null,

    painter.fillRect (10, 10, nextptr->getBreite(), nextptr->getHoehe(), Qt::green);

    will crash your program.

    This approach with static pointers is very bad. Don't do it. What is it that you want to achieve with the nextptr? Or with any of the pointers for that matter?

  • First of all, thank you very much for your reply, it already solved the problem.

    It was supposed to say

     class cRechteck nextRechteck (b, h, t, f);
        nextptr = &nextRechteck;

    instead of

     class cRechteck nextRechteck (b, h, t, f);
        newptr = &nextRechteck;

    Don't just copy and paste your own code snippets, kids! :)

    The program runs without crashing now.

    What would a good alternative to static pointers be? I wanted to use them because I didn't want to alter the program in main.cpp very much. It is a program from my computer science class. My thinking was that I could access the rectangle class member functions from my widget.cpp file.

  • Why do you want to paint inside the widget?

    Perhaps if you want this kind of free-hand painting use QGraphicsView, QGraphicsScene and QGraphicsRectItem.

    QGraphicsScene* pScene = new QGraphicsScene();
    QGraphicsView* pView = new QGraphicsView(pScene);

    and at some point

    auto pRect1 = pScene->addRect(...)
    auto pRect2 = pScene->addRect(...)
    auto pRect3 = pScene->addRect(...)

    or create your own custom item, subclassing QGraphicsItem (or perhaps QGraphicsRectItem) and re-implement what you think is needed.

    class MyRect : public QGraphicsItem
       MyRect(QRectF size);
    auto pMyRect1 = pScene->addItem(new MyRect(QRectF(...));
    auto pMyRect2 = pScene->addItem(new MyRect(QRectF(...));
    auto pMyRect3 = pScene->addItem(new MyRect(QRectF(...));

    The above code is not directly compilable but it can give you an idea of possible approaches.

    EDIT: Use QGraphicsObject instead of QGraphicsItem if you want to utilize signals and slots

Log in to reply