2016-02-04 46 views
0

我有一個Qt GUI應用程序,當我去幫助>關於時打開一個對話框。但是,如果我再次轉到「幫助」>「關於」,則會彈出另一個對話框。我試圖獲取它,以便已打開的About對話框是唯一可以打開的對話框(即不允許使用其他關於對話框)。我覺得這應該很簡單,但我不斷收到分段錯誤。這裏是我的代碼:限制QDialog窗口爲一個實例[Qt]?

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; 
} 

MyApp.cpp,當我擺脫if的,它的工作原理。但多次單擊幫助>關於(actionAbout_triggered)會打開一堆關於窗口。我只想要1.所以我想我會放入一個if語句,如果關於對話框已經打開,請不要創建另一個,而只是將其設置爲活動窗口。我遇到了分割錯誤。我知道這意味着它試圖訪問它不應該存在的內存,但我不知道爲什麼。

任何幫助將不勝感激。

回答

2

這樣的方式,一般是有一個模式對話框,您關於窗口。這樣

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

關於你的問題具體的東西,問題是你沒有初始化aboutDialogMyApp構造任何東西,所以它是「不定值」 - 可能不是null

設置aboutDialogMyApp構造爲空,以解決您的段錯誤。

+0

謝謝。那樣做了。我在'MyApp.cpp'中的MyApp構造函數中添加了'aboutDialog = NULL;'。我最初實現了你的模態例子,但決定我想要一個無模式的對話框。 – orbit

+0

謝謝!這是我第一次聽說模態對話框。 – alanwsx