【问题标题】:create custom Qwidget in Qt?在 Qt 中创建自定义 Qwidget?
【发布时间】:2011-06-23 09:19:04
【问题描述】:

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

}

【问题讨论】:

  • 在运行应用程序时构建没有问题,前两个小部件很好,当我点击导航第三个小部件时,它说错误(login.exe 文件已停止工作)

标签: qt qt4


【解决方案1】:

这是你的问题:

QHBoxLayout *hLayout;
hLayout->addWidget(button);

你忘了:

  • 在对象上实例化并分配 hLayout 以指向:

    hLayout = new QHBoxLayout();
  • 或现场实例化hLayout:

    QHBoxLayout hLayout;
    hLayout.addWidget(button);

基本上,您正在取消引用未初始化的指针,并且在大多数情况下您的应用程序会崩溃。

【讨论】:

  • @Exa 那是不必要的。无用的评论。
  • 在这种情况下,这是一个很好的建议。开始使用 Qt 时,您应该了解 C++ 的基础知识,例如内存分配。我试图提供建议,但您只是指出了您认为无用的评论。那么现在谁的评论更没用了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2020-10-22
  • 2019-06-03
相关资源
最近更新 更多