[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() -
Do you initialize the myPS pointer somewhere ?
Regards,
H. -
line4 : isn't initilisation ?
part of mainwindow.cpp:
1 void MainWindow::on_pb_test_1_clicked()
2 {
3 if (!myPS) {
4 myPS = new PortSetting(this);
}and private declaration in mainwindow.h ?
Do you have a suggestion ?
-
bq. line4 : isn’t initilisation ?
but you use (check) the pointer before (line 3 ).
Add
@myPs = NULL@to your main window constructor.
Regards,
H. -
works!, thank you very much.
I think i have to repeat some lectures :) -
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!
-
bq. It would be cleaner to use QPointer<T> for your data member.
May you be so kind and show me a minimal example of this approach, please.
-
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.
-
Isn't it a good idea to do so always ?
-
It only works on QObjects but besides that, I'd say no reason not to. Unless someone here wants to correct me.