Search code examples
c++qtaccess-violationqwidget

QWidget "access violation" exeption


A have a class, inherited from QWidget and Ui_Form (automaticaly generated class, appears when you create a .ui in Qt). It looks like

class MyClass: public QWidget, public Ui_Form {}

Ui_Form has some members, which connected with relevant widgets in the .ui file (for example, QLineEdits, QButtons, etc).

class Ui_Form {
public:
QLineEdit *fileNameEdit;

    void setupUi(QWidget *Form) {
    fileNameEdit = new QLineEdit(layoutWidget);
    fileNameEdit->setObjectName(QStringLiteral("fileNameEdit"));
    }
}

As MyClass is inherited from Ui_Form, I can use this membes. But, when I try to do something, I have an exeption "Access violation reading location". For example:

fileNameEdit->setText("String");

Can somebody give an advice?


Solution

  • The way you are incorporating the Ui_Form part is not how Qt proposes it by default. If you look into this button example you can see how the ui part is incorporated diferently:

    Header file

    #ifndef BUTTON_H
    #define BUTTON_H
    
    #include <QWidget>
    
    namespace Ui {
    class Button;
    }
    
    class Button : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit Button(int n, QWidget *parent = 0);
        ~Button();
    
    private slots:
        void removeRequested();
    
    signals:
        void remove(Button* button);
    private:
        Ui::Button *ui;
    };
    
    #endif // BUTTON_H
    

    CPP code

    #include "button.h"
    #include "ui_button.h"
    
    Button::Button(int n, QWidget *parent) :
        QWidget(parent),
        ui(new Ui::Button)
    {
        ui->setupUi(this);
        ui->pushButton->setText("Remove button "+QString::number(n));
        addAction(ui->actionRemove);
        connect(ui->actionRemove,SIGNAL(triggered()),this,SLOT(removeRequested()));
        connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(removeRequested()));
    }
    
    Button::~Button()
    {
        delete ui;
    }
    
    void Button::removeRequested()
    {
        emit remove(this);
    }
    

    The main difference is that I believe you are not calling Ui_From::setupUi function. It is clear to me that you do not need to follow the Qt suggested template (incorporating the ui as a class member rather than inheriting from it), however, it is much clearer from my point of view if you follow the Qt suggestions.