Qt Error: Debug Assertion Failed [How to Solve]

Purpose

I want to batch write controls into a layout. Qlabel and QWidget have about 20. It’s too hard to write line by line.

Qt Debug Assertion Failed! Error reporting reason

It is estimated that it is a wild pointer or a memory leak, because I often have the problem of memory access out of bounds when I use an array. As shown in the figure:

My error code

    QVBoxLayout* layout = new QVBoxLayout;//new creates a layout
    QLabel* labels = new QLabel[3];// here new an array of three QLabels;
    QStringList qstrList;
    qstrList<<u8 "Event list" << u8 "Assessment criteria" <<u8 "Subject list";//three strings
    for(int i = 0; i<3;i++){
        labels[i].setText(qstrList.at(i));//QLabel set text
        //---- set Qss----
        //---- set the font ----
    }
    for(int i = 0;i<3;i++){
        layout->addWidget(&labels[i]);//add QLabel to the layouts
    }

If it can be displayed, an error will be reported on the X of the closed window at the point, as shown in the figure:


My labels variable is not a member variable, which does not involve the problem of destruct before closing the window. If you change release to close the window, the word program abnormal end will also appear.

My solution

I’m used to using C + + arrays before. It’s better to replace QT batch setting components with containers such as qvector and qlist. Resolved Code:

QVBoxLayout* layout = new QVBoxLayout;//new has a layter
QVector<QLabel*> labels(3);//1. Now I know I have to use three so I limited it to three to prevent memory copies. You can also try the QList container 
//2. The type in the container can't be a component, only a pointer to a component.


    QStringList qstrList;
    qstrList<<u8 "EventList" << u8 "Assessment Criteria" <<u8 "SubjectList";//three strings
    for(int i = 0; i<3;i++){
        QLabel* label = new QLabel(qstrList.at(i));
        //---- set Qss----
        //---- set the font ----
    labels.append(label);
    }
    for(int i = 0;i<labels.size();i++){
        layout->addWidget(labels.at(i));
    }

Close the window again and there will be no error. I think the previous error report is the cause of the layout. I saw qtcreate warn me not to use the new control array.

Read More: