[solved] check whether form is initialised problem
-
I have a fresh project with mainwindow and a second designer form class named PortSetting.
I want to open the second form by clicking a pushbutton on mainwindow, but the application crashes.
" The program has unexpectedly finished."
part of mainwindow.cpp:
@void MainWindow::on_pb_test_1_clicked()
{
if (!myPS) {
myPS = new PortSetting(this);
}myPS->show(); myPS->raise(); myPS->activateWindow();}@
If i do not use the if-condition i can open as much forms as i want. Anyway i want to do this check,
but do not know where the error is.
mainwindow.h:
@#include <QMainWindow>
#include "portsetting.h"#include <QDebug>
namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();private slots:
void on_pb_test_1_clicked();private:
Ui::MainWindow *ui;
PortSetting *myPS;};@
portsetting.h :
@#include <QMainWindow>
#include <QDialog>namespace Ui {
class PortSetting;
}class PortSetting : public QDialog
{
Q_OBJECTpublic:
explicit PortSetting(QWidget *parent = 0);
~PortSetting();private:
Ui::PortSetting *ui;};
@portsetting.cpp:
@#include "portsetting.h"
#include "ui_portsetting.h"PortSetting::PortSetting(QWidget *parent) :
QDialog(parent),
ui(new Ui::PortSetting)
{
ui->setupUi(this);
}PortSetting::~PortSetting()
{
delete ui;
}@there is portsetting.ui but i think its not necessary to post here.
The form contains a single pushbutton connected to PortSetting close() -
To expand on Arnaut comment - your PortSetting* pointer would have a dirty but non-null value. That's why the if clause would not be entered (since it's not null) and you would try to call the show() on some random memory spot.
It would be cleaner to use QPointer<T> for your data member.
Edit: Whoops! I need to get used to refreshing my windows more often!
-
There's nothing to show really - you just declare your member as
@QPointer<PortSetting>@
And it behaves like PortSetting* but with a few benefits, including it being initialized with 0 without you explicitly writing it.
-
It only works on QObjects but besides that, I'd say no reason not to. Unless someone here wants to correct me.