我使用Qt Designer创建了2个窗口,我希望在第一个窗口中使用按钮“...”正确打开第二个窗口。我试着这样做,谢谢你的帮助。
firstwindow.cpp
#include "firstwindow.h"
#include "ui_firstwindow.h"
#include "secondwindow.h"
#include "ui_secondwindow.h"
FirstWindow::FirstWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::FirstWindow)
{
ui->setupUi(this);
ui->buttonapply->setText("Valider");
ui->buttoncancel->setText("Annuler");
ui->buttonetc->setText("...");
ui->buttonnext->setIcon(QIcon(":/Images/Images/Haut.png"));
ui->buttonprevious->setIcon(QIcon(":/Images/Images/Bas.png"));
connect(ui->buttonetc, SIGNAL(clicked()), this, SLOT(ShowSecondWindow()));
}
FirstWindow::~FirstWindow()
{
delete ui;
}
void FirstWindow::ShowSecondWindow()
{
SecondWindow window;
window.show();
}
firstwindow.h
#ifndef FIRSTWINDOW_H
#define FIRSTWINDOW_H
#include <QApplication>
#include <QWidget>
#include <QIcon>
#include "secondwindow.h"
#include "ui_secondwindow.h"
namespace Ui {
class FirstWindow;
}
class FirstWindow : public QWidget
{
Q_OBJECT
public:
explicit FirstWindow(QWidget *parent = 0);
~FirstWindow();
public slots:
void ShowSecondWindow();
private:
Ui::FirstWindow *ui;
SecondWindow *window;
};
#endif // FIRSTWINDOW_H
secondwindow.cpp
#include "firstwindow.h"
#include "ui_firstwindow.h"
#include "secondwindow.h"
#include "ui_secondwindow.h"
SecondWindow::SecondWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::SecondWindow)
{
ui->setupUi(this);
}
SecondWindow::~SecondWindow()
{
delete ui;
}
secondwindow.h
#ifndef SECONDWINDOW_H
#define SECONDWINDOW_H
#include <QWidget>
#include "firstwindow.h"
#include "ui_firstwindow.h"
namespace Ui {
class SecondWindow;
}
class SecondWindow : public QWidget
{
Q_OBJECT
public:
explicit SecondWindow(QWidget *parent = 0);
~SecondWindow();
private:
Ui::SecondWindow *ui;
};
#endif // SECONDWINDOW_H
的main.cpp
#include "firstwindow.h"
#include "ui_firstwindow.h"
#include "secondwindow.h"
#include "ui_secondwindow.h"
int main(int argc, char **argv)
{
QApplication program(argc, argv);
FirstWindow window;
window.setWindowTitle("BASELFI - Programme - © 2016 H2A");
window.setWindowIcon(QIcon(":/Images/Images/Bouclier.png"));
window.setFixedSize(340, 270);
window.show();
return program.exec();
}
答案 0 :(得分:2)
void FirstWindow::ShowSecondWindow()
{
SecondWindow window;
window.show();
}
此函数退出的那一刻,SecondWindow对象将立即关闭。因为它只在堆栈上创建,当超出范围时会自动销毁。
要解决此问题,您必须在堆/堆栈上将其作为FirstWindow类的数据成员分配或使其静态
分配到堆并使其成为数据成员:
class FirstWindow
{
....
private:
SecondWindow* window; // you must delete this in destructor
};
void FirstWindow::ShowSecondWindow()
{
window = new SecondWindow;
window->show();
}
或将其设为静态
void FirstWindow::ShowSecondWindow()
{
static SecondWindow window;
window.show();
}
或 分配到堆栈并使其成为FirstWindow类的数据成员:
class FirstWindow
{
....
private:
SecondWindow window; // initialize in constructor
};
void FirstWindow::ShowSecondWindow()
{
window.show();
}