【问题标题】:QWidget "access violation" exeptionQWidget“访问冲突”异常
【发布时间】:2017-09-26 07:08:51
【问题描述】:

A 有一个类,继承自 QWidget 和 Ui_Form(自动生成的类,在 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 继承的,我可以使用这个成员。但是,当我尝试做某事时,我有一个例外“访问冲突读取位置”。例如:

fileNameEdit->setText("String");

谁能给个建议?

【问题讨论】:

  • 你在 setupUi 运行之后再做吗?
  • A glance at the documentation 表明您需要在构造函数中调用 `setupUi(this)。你呢?
  • 是的,我运行了 setupUI。当然,成员不等于 NULL。但是,错误还是出现了

标签: c++ qt access-violation qwidget


【解决方案1】:

您合并Ui_Form 部分的方式与默认情况下的Qt proposes 不同。如果您查看此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 作为类成员而不是继承自它),但是,从我的角度来看,如果您遵循 Qt 建议会更清楚。

【讨论】:

  • 确实,通过多重继承包含Ui_Form并不是最好的解决方案:它增加了MyClass的用户的依赖,并且暴露了UI的成员(它们都是公共的,虽然你可以通过受保护的继承来避免这种情况)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多