I'm trying to write a simple app with singleton design in Qt. Below is the header file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
static MainWindow *getInstance();
~MainWindow();
private:
explicit MainWindow(QWidget *parent = 0);
static MainWindow *uniqueInstance;
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
And here is implementation file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow* MainWindow::uniqueInstance = new MainWindow();
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
MainWindow* MainWindow::getInstance()
{
return uniqueInstance;
}
Finally here is the main function:
#include <QApplication>
#include "mainwindow.h"
#include "QThread"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow *w = MainWindow::getInstance();
w->show();
return a.exec();
}
Building of my program is OK. But I receive a run-time error "QWidget: Must construct a QApplication before a QWidget". What should I do for solving this problem? I want to use this form of singleton to have a thread-safe program.
Thanks in advance for your helps.
Reza