earth
earth

Reputation: 955

Restrict QDialog window to one instance [Qt]?

I have a Qt GUI application that opens a dialog when I go to Help > About. However, if I go to Help > About again, another dialog pops up. I'm trying to get it so that the already opened About dialog is the only one that can be open (i.e. no additional About dialogs allowed). I feel like this should be simple, but I keep getting a Segmentation Fault. Here's my code:

myApp.h

#ifndef MYAPP_H
#define MYAPP_H

#include <QMainWindow>
#include "about.h"

namespace Ui {
class MyApp;
}

class MyApp : public QMainWindow // inherit all public parts of QMainWindow
{
  Q_OBJECT

public:
  explicit MyApp(QWidget* parent = 0);
  ~MyApp();

private slots:
  void on_actionAbout_triggered();

private:
  Ui::MyApp* ui;
  About* aboutDialog;
};

#endif // MYAPP_H

MyApp.cpp

#include "MyApp.h"
#include "ui_MyApp.h"
#include "about.h"

MyApp::MyApp(QWidget* parent) :
  QMainWindow(parent),
  ui(new Ui::MyApp)
{
  ui->setupUi(this);
}

MyApp::~MyApp()
{
  delete ui;
}

void MyApp::on_actionAbout_triggered()
{
  if (!aboutDialog) {
    aboutDialog = new About(this);  // create new window
  }
  aboutDialog->show();
  aboutDialog->activateWindow();
}

about.h

#ifndef ABOUT_H
#define ABOUT_H

#include <QDialog>

namespace Ui {
class About;
}

class About : public QDialog
{
  Q_OBJECT

public:
  explicit About(QWidget* parent = 0);
  ~About();

private:
  Ui::About* ui;
};

#endif // ABOUT_H

about.cpp

#include "about.h"
#include "ui_about.h"

About::About(QWidget* parent) :
  QDialog(parent),
  ui(new Ui::About)
{
  ui->setupUi(this);
}

About::~About()
{
  delete ui;
}

In MyApp.cpp, when I get rid of the if, it works. But clicking Help > About (actionAbout_triggered) multiple times will open a bunch of About windows. I just want 1. So I figured I'd put in an if statement that says, if the About dialog is already open, don't create another one and just make it the active window instead. I'm met with a Segmentation Fault. I know this means it's trying to access memory somewhere that it shouldn't be, but I don't know why.

Any help would be greatly appreciated.

Upvotes: 0

Views: 1679

Answers (1)

user3427419
user3427419

Reputation: 1779

The normal way of doing this is to have a modal dialog box for your About window. Something like this

void MyApp::on_actionAbout_triggered()
{
    About dlg(this);
    dlg.exec();
}

Regarding your question specifically, the problem is you did not initialize aboutDialog to anything in the MyApp constructor, so it is "undefined value" - probably not null.

Set aboutDialog to null in your MyApp constructor to solve your segfaults.

Upvotes: 3

Related Questions