我创建了示例应用程序,其中使用了 UI 表单中的前两个 Qwidget,第三个小部件是自定义的。我创建了一个 cpp 文件和头文件。运行应用程序时构建时没有问题,前两个小部件正常,当我单击导航第三个小部件时,它说错误(login.exe 文件已停止工作) 我的头文件是:
#ifndef LISTWIDGET_H
#define LISTWIDGET_H
#include <QObject>
#include <QWidget>
#include <QtGui>
#include <QPushButton>
class listWidget : public QWidget
{
Q_OBJECT
public:
explicit listWidget(QWidget *parent=0);
~listWidget();
public:
QPushButton *button;
signals:
};
#endif // LISTWIDGET_H
我的cpp文件是:
#include "listwidget.h"
#include <QHBoxLayout>
#include <QObject>
#include <QWidget>
#include <QtGui>
listWidget::listWidget(QWidget *parent):QWidget(parent)
{
resize(100,100);
button = new QPushButton("Click here to go back");
QHBoxLayout *hLayout;
hLayout->addWidget(button);
setLayout(hLayout);
}
listWidget::~listWidget()
{
}
最佳答案
这是您的问题:
QHBoxLayout *hLayout;
hLayout->addWidget(button);
您忘记了:
实例化并分配 hLayout 指向的对象:
hLayout = new QHBoxLayout();
或当场实例化 hLayout:
QHBoxLayout hLayout; hLayout.addWidget(button);
基本上,您正在取消引用未初始化的指针,并且在大多数情况下您的应用程序会崩溃。
关于qt - 在 Qt 中创建自定义 Qwidget?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4932615/