Fahmid
Fahmid

Reputation: 180

Qt - Open single instance of a window

How do I check if a window/dialog is already open? I used this code to open a new dialog box but everytime I click it the dialog keeps on opening. Obviously not the way settings dialog works.

Class *someClass = new Class();
someclass->show();

Upvotes: 0

Views: 4121

Answers (4)

Marcus Frenkel
Marcus Frenkel

Reputation: 711

Use QPointer:

QPointer<MyDialog> dialog = new MyDialog(this);
dialog->show();
...
if (dialog) dialog->show();

If dialog exists it will be shown. If it is deleted in the meantime, it will hold 0 instead of an invalid address, and the last line will never be executed - it will not be shown but you can recreate it if needed.

Upvotes: 1

rpsml
rpsml

Reputation: 1498

In your calling class (or main application class, or something similar) define a pointer to the class:

dialogclass *someclass;

In the constructor of that main class, initialize the dialog class:

someclass = NULL;

When you want to show the dialog, do something along these lines:

if (!someclass) someclass = new dialogclass();  // Creates a dialog instance if it does not already exist 
if (!someclass->isVisible()) someclass->show(); // Only shows the dialog if it is not already shown.

Upvotes: 1

Kamran Amini
Kamran Amini

Reputation: 1062

You can make an static pointer on your window class. It allows you to store last opened window object.

class MyWindow : public QWidget {
  public :
    static MyWindow* instance;

  ...
}

Whenever you make a new instance you can set instance. When the instance is null you can make a new window. When you want to close the opened window, you should make instance null again. This allows you to have only one open window.

if (MyWindow::instance == NULL) {
  MyWindow *w = new MyWindow(...);
  MyWindow::instance = w;
}

This design pattern is called Singleton and it allows you to have only one object per a class. Also, this is a bit different because in Singleton, constructor is not public and factory method should be used for making an object but it is similar.

Upvotes: 0

lukad
lukad

Reputation: 17863

In your code you create a new window/widget/dialog everytime. Initialize *someClass somewhere else and then only show it.

class Foo
{
public:
    Foo() { someClass = new SomeClass() }
    void fooClicked() { someClass->show() }

private:
    SomeClass *someClass;
};

Upvotes: 1

Related Questions