为什么应用程序在Qt中按下提交按钮时崩溃了?

时间:2017-10-02 19:50:06

标签: c++ qt c++11

以下是我对确认窗口的定义(在主窗口中点击提交按钮时打开的窗口)。 的 confirmwindow.h

#ifndef CONFIRMWINDOW_H
#define CONFIRMWINDOW_H

#include <QDialog>

namespace Ui {
class ConfirmWindow;
}

class ConfirmWindow : public QDialog
{
    Q_OBJECT

public:
    explicit ConfirmWindow(QWidget *parent = 0);
    ConfirmWindow(QString name);
    ~ConfirmWindow();

private:
    Ui::ConfirmWindow *ui;
};

#endif // CONFIRMWINDOW_H

confirmwindow.cpp中,我按以下方式定义

#include "confirmwindow.h"
#include "ui_confirmwindow.h"

ConfirmWindow::ConfirmWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConfirmWindow)
{
    ui->setupUi(this);
}

ConfirmWindow::~ConfirmWindow()
{
    delete ui;
}

ConfirmWindow::ConfirmWindow(QString name)
{
    ui->label_show_name->setText(name);
}

当我运行该程序时,一切顺利,直到我按下提交按钮,该应用程序在控制台中以The program has unexpectedly finished.

的消息崩溃应用程序

mainwindow.cpp我称之为

void MainWindow::on_pushButton_submit_clicked()
{
    ConfirmWindow confirm_window(ui->lineEdit_name->text());
    confirm_window.exec();
}

我想,我在confirmwindow.cpp文件中以错误的方式定义构造函数。

1 个答案:

答案 0 :(得分:0)

这一行:

ConfirmWindow confirm_window(ui->lineEdit_name->text());

将使用构造函数ConfirmWindow创建ConfirmWindow(String)。但是,在此构造函数中,您不初始化ConfirmWindow::ui,结果是ui->label_show_name具有未定义的行为。

快速修复:

ConfirmWindow::ConfirmWindow(QString name) :
   ui(new Ui::ConfirmWindow) // initialize UI
{
    ui->label_show_name->setText(name);
}

以下是一些补救措施:

#ifndef CONFIRMWINDOW_H
#define CONFIRMWINDOW_H

#include <QDialog>

namespace Ui {
class ConfirmWindow;
}

class ConfirmWindow : public QDialog
{
    Q_OBJECT

public:
    explicit ConfirmWindow(QWidget *parent = 0);
    explicit ConfirmWindow(QString name, QWidget *parent = 0); // Prevent implicit conversion from QString
    ~ConfirmWindow();

private:
    Ui::ConfirmWindow *ui = nullptr; // Require C++11, but will make easier to debug cases where you forgot to initialize ui
};

#endif // CONFIRMWINDOW_H

-

#include "confirmwindow.h"
#include "ui_confirmwindow.h"

ConfirmWindow::ConfirmWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConfirmWindow)
{
    ui->setupUi(this);
}

ConfirmWindow::~ConfirmWindow()
{
    delete ui;
}

ConfirmWindow::ConfirmWindow(QString name, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConfirmWindow)
{
    ui->label_show_name->setText(name);
}