QT单例的简单使用

单例的.h文件

#ifndef MSLEEP_H
#define MSLEEP_H

#include 
#include 

class msleep
{

public:
//    QString getInstanceName() const;
    static msleep& getInstance(); //获取msleep的唯一对象
//    static void release();

    msleep();    //私有的构造函数
    ~msleep();  //析构函数

    bool sleep(unsigned int msec);

private:
    msleep(const msleep&other); //拷贝构造函数
    msleep& operator=(const msleep&other); //赋值运算操作符
    static QMutex mutex;
    static QScopedPointer<msleep> instance; //静态的QScopedPointer的变量instance
signals:

};

#endif // MSLEEP_H

单例的.cpp文件

#include "msleep.h"

#include 
#include 

QMutex msleep::mutex;
QScopedPointer<msleep> msleep::instance;

msleep& msleep::getInstance() {
    if (instance.isNull()) {
        mutex.lock();
        if (instance.isNull()) {
            instance.reset(new msleep());  //QScopedPointer的reset方法
        }
        mutex.unlock();
    }

    return *instance.data(); //返回指向对象的常量指针
}

//我发现不管是qt自带的Sleep(100);还是如下代码,主线程都会卡死
//但还是感谢这位兄台的代码https://blog.csdn.net/Mohammedzy/article/details/127725203
bool msleep::sleep(unsigned int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while (QTime::currentTime() < dieTime)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    return true;
}

msleep::msleep()
{

}

msleep::~msleep()
{

}

使用单例的.cpp代码

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "msleep.h"//引入

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
	
	msleep::getInstance().sleep(20);//使用。这里仅做使用示例,睡眠在这里是会卡死主线程的
    
}

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

你可能感兴趣的:(c++,qt)