qt - 在 Qt 中创建自定义 Qwidget?

标签 qt qt4

我创建了示例应用程序,其中使用了 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/

相关文章:

c++ - Qt的foreach表达式需要深拷贝?

qt - 将父级传递给 Qt 类构造函数的目的是什么?

c++ - Qt 中那些带括号数字的注释是什么?

c++ - 没有这样的插槽按钮QT

c++ - 取消选中/选中 QCheckBox 后使 QLabel 不可见/可见

c++ - "undefined reference to ' QScriptEngine::QScriptEngine()"

qt4 - 在 QTreeView 上的子项上设置小部件

c++ - Qt中的单例类问题

drag-and-drop - 从 QTableView/QSqlTableModel 中拖动一个项目

c++ - 如何在 QFileDialog 上设置选定的过滤器?