【问题标题】:Qt5 custom QDialog without using qt creatorQt5 自定义 QDialog 不使用 qt creator
【发布时间】:2018-06-27 18:50:51
【问题描述】:

我正在尝试编写一个自定义的纯 C++ QDialog,以便我可以创建一个基类并在以后继承它。以下是在 QDialog 中显示 QLabel 的代码:

“EDLController.h”

#ifndef EDLController_h
#define EDLController_h

#include <QDialog>

class EDLController : public QDialog {
    Q_OBJECT
public:
    EDLController(QWidget *parent = nullptr);
};
#endif

“EDLController.cpp”

EDLController::EDLController(QWidget *parent) : QDialog(parent) {
    QVBoxLayout vBoxLayout;

    QLabel label("text");
    vBoxLayout.addWidget(&label);

    setLayout(&vBoxLayout);
    setWindowTitle("test");
}

“main.cpp”

int main(int argc, char *argv[]) {    
    QApplication app(argc, argv);

    EDLController *w = new EDLController();
    w->show();
    return app.exec();
}

但是,它显示了一个标题正确的空窗口: image

程序在 Raspberry Pi (Raspbian) 上运行。谁能帮我找出问题所在。

【问题讨论】:

  • vBoxLayoutEDLController ctor 的本地对象,一旦超出范围就会被销毁。使其成为EDLController 的成员。

标签: c++ qt5 raspbian


【解决方案1】:

问题在于您的标签声明。您创建一个局部变量标签,它在 EDLController 构造函数的末尾被销毁。 您可以通过像这样继承 QLabel 来确认这一点:


class MyLabel : public QLabel
{
    Q_OBJECT
public:
    MyLabel(const QString& str, QWidget* parent = nullptr) : QLabel(str,parent){}
    ~MyLabel() {qDebug() << "LABEL DELETED";}
};

在实例化 QDialog 时将记录“标签已删除”消息。 当然,您不能显示已删除的小部件。

正确的代码如下:


 QLabel* label = new  QLabel("text");
 vBoxLayout.addWidget(label);

当父项(您的对话框)被销毁时,标签将被销毁。

【讨论】:

    【解决方案2】:

    vBoxLayoutlabel 将在 EDLController 构造函数退出时被销毁,因为它们是局部变量。在堆上创建新实例以避免这种情况:

    EDLController::EDLController(QWidget *parent)
        : QDialog(parent)
    {
        QVBoxLayout * vBoxLayout = new QVBoxLayout(this);
        QLabel * label = new QLabel(this);
        label->setText("test");
        vBoxLayout->addWidget(label);
    
        setLayout(vBoxLayout);
        setWindowTitle("test");
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2021-07-04
      • 2016-11-05
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多