实现一个widget只能被打开一个(单例模式)
开发环境:qt5,mingw
功能:点击按钮打开一个widget窗口,但widget只能打开一个
知识点:单例模式,信号槽
#ifndef FORM_H #define FORM_H #include <QWidget> namespace Ui { class Form; } class Form : public QWidget { Q_OBJECT public: explicit Form(QWidget *parent = nullptr); ~Form(); static Form* getInstance(); private: Ui::Form *ui; static Form* myInstance; }; #endif // FORM_H
#include "Form.h" #include "ui_Form.h" Form *Form::myInstance=NULL; Form::Form(QWidget *parent) : QWidget(parent), ui(new Ui::Form) { ui->setupUi(this); } Form::~Form() { delete ui; } Form *Form::getInstance() { if(myInstance==NULL){ myInstance=new Form(); } return myInstance; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include"Form.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); public slots: void onBtnClick(); private: Ui::MainWindow *ui; Form *fm; }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //让onBtnClick 接受 bnt2的点击信号 connect(ui->btn2,&QPushButton::clicked,this,&MainWindow::onBtnClick); } MainWindow::~MainWindow() { delete ui; } void MainWindow::onBtnClick() { fm=Form::getInstance(); fm->show(); }#QT##C##单例模式#