我用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();
}
最佳答案
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();
}