QWidget "access violation" 豁免

QWidget "access violation" exeption

A 有一个 class,继承自 QWidget 和 Ui_Form(自动生成 class,当您在 Qt 中创建一个 .ui 时出现)。看起来像

class MyClass: public QWidget, public Ui_Form {}

Ui_Form有一些成员,与.ui文件中的相关小部件(例如QLineEdits、QButtons等)相关联。

class Ui_Form {
public:
QLineEdit *fileNameEdit;

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

由于MyClass继承自Ui_Form,我可以使用这个成员。但是,当我尝试做某事时,出现异常 "Access violation reading location"。例如:

fileNameEdit->setText("String");

有人可以给个建议吗?

您合并 Ui_Form 部分的方式与 Qt proposes it by default. If you look into this button example 您看到的 ui 部分的合并方式不同:

头文件

#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代码

#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);
}

主要区别在于我相信您没有调用 Ui_From::setupUi 函数。我很清楚你不需要遵循 Qt 建议的模板(将 ui 作为 class 成员而不是从它继承),但是,从我的角度来看它更清楚如果您遵循 Qt 建议。