以下是我对确认窗口的定义(在主窗口中点击提交按钮时打开的窗口)。 的 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
文件中以错误的方式定义构造函数。
答案 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);
}