在Qt项目中用到静态单例类,本文介绍单例类定义,已经静态成员变量的处理。本文代码在Qt5.12中调试,实现页面下子控件随页面缩放的功能。
1. 头文件定义
#ifndef CCOMMON_H
#define CCOMMON_H
#include <QWidget>
#include <QApplication>
#include <QtDebug>
#define STD_WIDTH 1920
#define STD_HIGHT 1080
class MyCommon : public QWidget
{
Q_OBJECT
public:
explicit MyCommon(QWidget *parent = nullptr);
~MyCommon();
static MyCommon *instance();
static void scalWidget(QWidget *widget, float xc = 1, float yc = 1);
signals:
public slots:
private:
static float xScal, yScal; // 静态成员变量
static QRect mScreenRect; // 静态成员变量
static MyCommon *self;//单例模式
};
#endif // CCOMMON_H
头文件中定义的静态成员变量要在cpp文件中实例化,否则会报错:
release/ccommon.o:ccommon.cpp:(.rdata$.refptr._ZN8MyCommon5yScalE[.refptr._ZN8MyCommon5yScalE]+0x0): undefined reference to `MyCommon::yScal'
release/ccommon.o:ccommon.cpp:(.rdata$.refptr._ZN8MyCommon5xScalE[.refptr._ZN8MyCommon5xScalE]+0x0): undefined reference to `MyCommon::xScal'
release/ccommon.o:ccommon.cpp:(.rdata$.refptr._ZN8MyCommon11mScreenRectE[.refptr._ZN8MyCommon11mScreenRectE]+0x0): undefined reference to `MyCommon::mScreenRect'
release/ccommon.o:ccommon.cpp:(.rdata$.refptr._ZN8MyCommon4selfE[.refptr._ZN8MyCommon4selfE]+0x0): undefined reference to `MyCommon::self'
3. CPP文件定义
#include "ccommon.h"
#include <QDesktopWidget>
MyCommon *MyCommon::self = nullptr;
float MyCommon::xScal;
float MyCommon::yScal;
QRect MyCommon::mScreenRect;
MyCommon::MyCommon(QWidget *parent) : QWidget(parent)
{
mScreenRect = QApplication::desktop()->screenGeometry();
}
MyCommon::~MyCommon()
{
if (self != nullptr)
{
delete self;
}
}
MyCommon *MyCommon::instance()
{
if(!self)
{
self = new MyCommon();
}
return self;
}
void MyCommon::scalWidget(QWidget *widget, float xc, float yc)
{
if (widget == nullptr)
{
return;
}
xScal = (float)mScreenRect.width() * xc / STD_WIDTH;
yScal = (float)mScreenRect.height() * yc / STD_HIGHT;
//qDebug() << mScreenRect << xScal << yScal;
int x, y, w, h;
QRect rect = widget->geometry();
x = rect.x();
y = rect.y();
w = rect.width();
h = rect.height();
widget->setGeometry(x*xScal, y*yScal, w*xScal, h*yScal);
int m_fontSize = (widget->font().pointSize() * xScal);
QString style = tr("font: %1pt;").arg(m_fontSize);
QString str = widget->styleSheet();
if(str.contains("font:"))
{
str = str.replace(QRegExp("font: \\d+pt"), QString("font: %1pt").arg(m_fontSize));
}
else
{
QString buf = widget->metaObject()->className();
if(buf == "QPushButton")
{
str.append(style);
}
}
widget->setStyleSheet(str);
}