在头文件<QtGlobal>中包含了Qt的全局函数,现在就这些全局函数一一详解。
1.qAbs
原型:
template <typename T> T qAbs(const T &t)
一个用于计算绝对值的函数。它可以用于计算各种数值类型的绝对值,包括整数、浮点数等
示例如下:
#include <QtCore/QCoreApplication>
#include <QtCore/qmath.h>
#include <iostream>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);int num1 = -5;double num2 = -3.14;// 使用qAbs计算绝对值int absNum1 = qAbs(num1);double absNum2 = qAbs(num2);std::cout << "The absolute value of " << num1 << " is " << absNum1 << std::endl;std::cout << "The absolute value of " << num2 << " is " << absNum2 << std::endl;return a.exec();
}
2.qAsConst
原型:
template <typename T> typename std::add_const<T>::type &qAsConst(T &t)
template <typename T> void qAsConst(T&& t)
官方的解释:
- 这个函数实现了C++17标准中的std::as_const()函数的功能,将一个非常量的左值转为常量的左值。
- 增加qAsConst函数是为了Qt自己的非const 的容器能实现C++11标准的基于范围的循环。
- 该函数主要用于qt容器在隐式共享中不被detach。
最直观的的
作用就是将一个对象转换为常量引用。在 C++ 里,如果你有一个非 const
对象,而你又希望在某些场景下把它当作 const
对象来使用(例如传递给一个只接受 const
引用的函数),qAsConst
就可以发挥作用。
从上文的描述,我们知道下面的代码:
QString s = ...;
for (QChar ch : s) // detaches 's' (performs a deep-copy if 's' was shared)process(ch);
当s被修改时,将会导致s被detach,继而再执行深拷贝,而下面的代码s不会被detach,当然也就不会再执行深拷贝了
for (QChar ch : qAsConst(s)) // ok, no detach attemptprocess(ch);
当然,在这种情况下,你也许会说,像下面那样将s声明为const,也不会执被detach:
const QString s = ...;for (QChar ch : s) // ok, no detach attempt on const objectsprocess(ch);
但是在编程时、在现实中,声明为const往往不容易做到。对Qt自己实现的容器如:QVector、QMap、 QHash、QLinkedList、QList等,如果一定要用基于for(var : container)范围的循环,则请用如下形式:
for(var : qAsConst(container))
3.qBound
原型:
template <typename T> const T &qBound(const T &min, const T &val, const T &max)
其功能是把一个值限定在指定的最小值和最大值范围内。当该值小于最小值时,它会返回最小值;当该值大于最大值时,它会返回最大值;若该值处于最小值和最大值之间,则直接返回该值。
在实际开发中,qBound
函数常用于以下场景:
- 限制数值范围:当你要确保某个数值处于特定区间内时,可使用该函数。比如,调整音量、进度条等控件的值时,需要保证其在有效范围内。
- 避免越界访问:在处理数组、列表等数据结构时,用
qBound
函数可防止索引越界。
示例如下:
#include <QCoreApplication>
#include <QVector>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);QVector<int> numbers = {1, 2, 3, 4, 5};int index = 10;int validIndex = qBound(0, index, static_cast<int>(numbers.size() - 1));if (validIndex < numbers.size()) {qDebug() << "Value at index:" << numbers[validIndex];} else {qDebug() << "Index is out of bounds.";}return a.exec();
}
在这个例子中,index
的值为 10,超出了 numbers
向量的有效索引范围。qBound
函数会将 index
限制在 0 到 numbers.size() - 1
之间,避免了越界访问。
4.qConstOverload、qNonConstOverload
原型:
template <typename T> auto qConstOverload(T memberFunctionPointer);
template <typename T> auto qNonConstOverload(T memberFunctionPointer);
主要用于解决 C++ 中函数重载和信号槽连接时的类型推导问题,特别是在连接 const
和非 const
版本的重载函数时。
C/C++中重载函数取地址的方法_qt c++ 绑定重载信号-CSDN博客
如:
struct Foo {void overloadedFunction(int, const QString &);void overloadedFunction(int, const QString &) const;};... qConstOverload<int, const QString &>(&Foo::overloadedFunction)... qNonConstOverload<int, const QString &>(&Foo::overloadedFunction)
示例如下:
#include <QCoreApplication>
#include <QObject>
#include <QDebug>class MyClass : public QObject
{Q_OBJECT
public:explicit MyClass(QObject *parent = nullptr) : QObject(parent) {}// 非 const 版本的重载函数void myFunction(int value) {qDebug() << "Non-const myFunction called with value:" << value;}// const 版本的重载函数void myFunction(int value) const {qDebug() << "Const myFunction called with value:" << value;}
};#include "main.moc"int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);MyClass obj;const MyClass constObj;// 连接 const 版本的 myFunctionQObject::connect(&constObj, qConstOverload<int>(&MyClass::myFunction), [](int value) {qDebug() << "Slot called with value:" << value;});// 发送信号调用 const 版本的 myFunctionconstObj.myFunction(42);return a.exec();
}
5.qEnvironmentVariable
原型:
//该函数用于获取指定名称的环境变量的值。若环境变量存在,就返回其值;若不存在,则返回一个空字符串。
QString qEnvironmentVariable(const char *varName)//此函数同样是获取指定名称的环境变量的值。要是环境变量不存在,就返回指定的默认值。
QString qEnvironmentVariable(const char *varName, const QString &defaultValue)//通过 ok 变量判断转换是否成功。若成功,输出转换后的整数值;若失败,输出错误信息。
int qEnvironmentVariableIntValue(const char *varName, bool *ok = nullptr)//该函数用于检查指定名称的环境变量是否被设置。若已设置,返回 true;反之,返回 false。
bool qEnvironmentVariableIsEmpty(const char *varName)//此函数用于检查指定名称的环境变量是否为空。若为空(即变量存在但值为空字符串)或者变量未设置,返回 true;否则返回 false。
bool qEnvironmentVariableIsSet(const char *varName)
qEnvironmentVariable
是 Qt 中用于访问系统环境变量的一组函数。环境变量是操作系统中存储的键值对,可用于存储各种配置信息,像路径、系统设置等。在 Qt 程序里,你可以借助这些函数获取环境变量的值,以实现特定的配置或功能。
示例如下:
#include <QCoreApplication>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);// 获取 PATH 环境变量的值QByteArray pathValue = qEnvironmentVariable("PATH");if (!pathValue.isEmpty()) {qDebug() << "PATH environment variable:" << pathValue;} else {qDebug() << "PATH environment variable is not set.";}// 获取一个可能不存在的环境变量,并提供默认值QByteArray customValue = qEnvironmentVariable("MY_CUSTOM_VARIABLE", "default_value");qDebug() << "MY_CUSTOM_VARIABLE:" << customValue;// 检查环境变量是否设置bool isSet = qEnvironmentVariableIsSet("JAVA_HOME");qDebug() << "JAVA_HOME is set:" << isSet;// 检查环境变量是否为空bool isEmpty = qEnvironmentVariableIsEmpty("TEMP");qDebug() << "TEMP is empty:" << isEmpty;return a.exec();
}
6.qExchange
原型:
template <typename T, typename U> T qExchange(T &obj, U &&newValue)
其功能和标准库中的 std::exchange
类似,用于将一个对象的值替换为新值,并返回该对象的旧值。在 Qt 中使用 qExchange
可以简化代码逻辑,尤其在需要更新对象状态并保留旧值的场景中非常有用。
C++14之std::exchange的使用和原理分析-CSDN博客
qExchange
常用于以下场景:
- 状态更新:在更新对象的状态时,需要保留对象的旧状态,以便后续使用。
- 资源管理:在释放或转移资源时,需要返回旧资源的所有权。
示例如下:
#include <QCoreApplication>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);int* oldPtr;int value1 = 10;int value2 = 20;int* ptr = &value1;// 使用 qExchange 更新 ptr 的值,并获取旧值oldPtr = qExchange(ptr, &value2);qDebug() << "Old pointer value:" << *oldPtr;qDebug() << "New pointer value:" << *ptr;return a.exec();
}
7.qFloatDistance
原型:
quint32 qFloatDistance(float a, float b)
quint64 qFloatDistance(double a, double b)
返回a和b之间可表示的浮点数。
此函数提供了一种类似于 qFuzzyCompare() 的浮点数近似比较的替代方法。但是,它返回两个数字之间的距离,这使调用者可以选择接受的错误。误差是相对的,例如1.0E-5和1.00001E-5之间的距离将为110,而1.0E36和1.00001-E36之间的距离为127。
如果浮点比较需要一定的精度,则此函数很有用。因此,如果a和b相等,它将返回0。对于32位浮点数,它将返回的最大值是4278190078。这是-FLT_MAX和+FLT_MAX之间的距离。
如果任何参数为Infinite或NaN,则函数不会给出有意义的结果。您可以通过调用qIsFinite()来检查这一点。
返回值可以被视为“错误”,因此,如果你想比较两个32位浮点数,而你所需要的只是一个近似的24位精度,你可以这样使用这个函数:
if (qFloatDistance(a, b) < (1 << 7)) { // The last 7 bits are not// significant// precise enough
}
8.qInstallMessageHandler
原型:
//格式化日志消息的函数
QString qFormatLogMessage(QtMsgType type, const QMessageLogContext &context, const QString &str);//安装日志钩子函数
void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);
QtMessageHandler qInstallMessageHandler(QtMessageHandler handler);
当你想要自定义日志输出的格式,比如添加时间戳、日志级别标识、文件和行号等额外信息时,就可以使用 qFormatLogMessage
函数。
示例如下:
#include <QCoreApplication>
#include <QDebug>
#include <QDateTime>
#include <QMessageLogContext>// 自定义日志消息格式化函数
QByteArray customFormatLogMessage(QtMsgType type, const QMessageLogContext &context, const QString &message)
{QString level;switch (type) {case QtDebugMsg:level = "DEBUG";break;case QtInfoMsg:level = "INFO";break;case QtWarningMsg:level = "WARNING";break;case QtCriticalMsg:level = "CRITICAL";break;case QtFatalMsg:level = "FATAL";break;default:level = "UNKNOWN";}QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");QString formattedMessage = QString("[%1] [%2] [%3:%4 %5] %6").arg(timestamp).arg(level).arg(context.file ? context.file : "").arg(context.line).arg(context.function ? context.function : "").arg(message);return formattedMessage.toUtf8();
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);// 设置自定义的日志消息处理函数qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &context, const QString &message) {QByteArray formattedMessage = customFormatLogMessage(type, context, message);fprintf(stderr, "%s\n", formattedMessage.constData());});// 输出不同级别的日志消息qDebug() << "This is a debug message";qInfo() << "This is an info message";qWarning() << "This is a warning message";qCritical() << "This is a critical message";return a.exec();
}
1)自定义格式化函数 customFormatLogMessage:
根据日志消息的类型 type 确定日志级别字符串 level。
获取当前的时间戳 timestamp。
利用 QString::arg 方法将时间戳、日志级别、文件路径、行号、函数名和日志消息内容组合成一个格式化的字符串 formattedMessage。
将格式化后的字符串转换为 QByteArray 类型并返回。
2)设置自定义日志消息处理函数:
使用 qInstallMessageHandler 函数设置一个自定义的日志消息处理函数,在该函数中调用customFormatLogMessage 对日志消息进行格式化,并将格式化后的消息输出到标准错误流。
3)输出不同级别的日志消息:
使用 qDebug、qInfo、qWarning、qCritical 等宏输出不同级别的日志消息,这些消息会经过自定义的格式化处理后输出。
通过这种方式,你可以根据自己的需求灵活定制日志输出的格式。
9.qSetMessagePattern
原型:
//设置日志格式的函数
void qSetMessagePattern(const QString &pattern);
qSetMessagePattern
是一个全局设置,会影响整个应用程序的消息输出格式。
常用占位符
%{appname}
:应用程序的名称。%{category}
:消息的类别。%{file}
:输出消息的源文件名称。%{function}
:输出消息的函数名称。%{line}
:输出消息的源文件中的行号。%{message}
:实际的消息内容。%{pid}
:进程 ID。%{threadid}
:线程 ID。%{type}
:“debug”、”warning”、”critical”或”fatal”。%{time process}
:从进程启动开始的时间。%{time boot}
:从系统启动开始的时间。%{time [format]}
:当前时间,[format]
是一个可选的时间格式字符串,遵循QDateTime::toString
的格式规则。%{type}
:消息的类型(如debug
、warning
、critical
、fatal
)。- %{backtrace [depth=N] [separator=”…”]}: 很多平台不支持,暂略…
还可以使用条件类型,%{if-debug}, %{if-info} %{if-warning}, %{if-critical}
或 %{if-fatal}
后面跟着一个%{endif}
。如果类型匹配,%{if-*}
和 %{endif}
之间的内容会被打印。
最后,如果类别不是默认的一个,%{if-category} ... %{endif}
之间的内容将被打印。
示例如下:
int main(int argc, char **argv)
{QApplication app(argc, argv);// 改变缺省消息处理程序的输出qSetMessagePattern("Message:%{message} File:%{file} Line:%{line} Function:%{function} DateTime:%{time [yyyy-MM-dd hh:mm:ss ddd]}");// 打印信息qDebug("This is a debug message.");qInfo("This is a info message.");qWarning("This is a warning message.");qCritical("This is a critical message.");qFatal("This is a fatal message.");...return app.exec();
}
输出如下:
Message:This is a debug message. File:..\MessagePattern\main.cpp Line:138 Function:main DateTime:[2025-04-28 15:21:40 周一]
Message:This is a info message. File:..\MessagePattern\main.cpp Line:139 Function:main DateTime:[2025-04-28 15:21:40 周一]
Message:This is a warning message. File:..\MessagePattern\main.cpp Line:140 Function:main DateTime:[2025-04-28 15:21:40 周一]
Message:This is a critical message. File:..\MessagePattern\main.cpp Line:141 Function:main DateTime:[2025-04-28 15:21:40 周一]
Message:This is a fatal message. File:..\MessagePattern\main.cpp Line:142 Function:main DateTime:[2025-04-28 15:21:40 周一]
如果 QT_MESSAGE_PATTERN 环境变量被设置:
选择:项目 -> 构建环境,添加环境变量:
QT_MESSAGE_PATTERN = [%{type}] %{appname} (%{file}:%{line}) - %{message}
int main(int argc, char **argv)
{QApplication app(argc, argv);// 改变缺省消息处理程序的输出qSetMessagePattern("Message:%{message} File:%{file} Line:%{line} Function:%{function} DateTime:%{time [yyyy-MM-dd hh:mm:ss ddd]}");// 打印信息qDebug("This is a debug message.");qInfo("This is a info message.");qWarning("This is a warning message.");qCritical("This is a critical message.");qFatal("This is a fatal message.");...return app.exec();
}
输出如下:
[debug] MessagePattern (..\MessagePattern\main.cpp:138) - This is a debug message.
[info] MessagePattern (..\MessagePattern\main.cpp:139) - This is a info message.
[warning] MessagePattern (..\MessagePattern\main.cpp:140) - This is a warning message.
[critical] MessagePattern (..\MessagePattern\main.cpp:141) - This is a critical message.
[fatal] MessagePattern (..\MessagePattern\main.cpp:142) - This is a fatal message.
如上所述,这时即使我们使用了qSetMessagePattern也无济于事,因为,环境变量优先。
10.qFpClassify
原型:
int qFpClassify(double val);
qFpClassify
是 Qt 提供的一个用于对浮点数进行分类的函数。在处理浮点数时,有时需要判断一个浮点数是正常数、零、无穷大、NaN(非数字)等不同类型,qFpClassify
就可以帮助你完成这样的分类工作。
该函数返回一个整数,代表浮点数的分类类型,常见的返回值及其含义如下:
FP_NAN
:表示value
是一个非数字(NaN)。FP_INFINITE
:表示value
是无穷大(正无穷或负无穷)。FP_ZERO
:表示value
是零(正零或负零)。FP_SUBNORMAL
:表示value
是一个非正规数(比最小的正规数还要小)。FP_NORMAL
:表示value
是一个正常的浮点数。
示例如下:
#include <QCoreApplication>
#include <QDebug>
#include <cmath>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);double normalNumber = 3.14;double zero = 0.0;double infinity = std::numeric_limits<double>::infinity();double nan = std::numeric_limits<double>::quiet_NaN();qDebug() << "Classification of normal number:" << qFpClassify(normalNumber);qDebug() << "Classification of zero:" << qFpClassify(zero);qDebug() << "Classification of infinity:" << qFpClassify(infinity);qDebug() << "Classification of NaN:" << qFpClassify(nan);return a.exec();
}
注意事项
- 要使用
std::numeric_limits
来获取无穷大和非数字的值,需要包含<cmath>
头文件。 - 该函数对于双精度浮点数进行分类,如果你需要处理单精度浮点数,可以考虑使用
qFpClassify(float value)
版本的函数。
11.qFuzzyCompare
原型:
bool qFuzzyCompare(double p1, double p2);
bool qFuzzyCompare(float p1, float p2);
浮点数比较大小,重载了float和double版本。
qFuzzyCompare
函数的比较原理是通过判断两个浮点数的差值是否小于一个很小的阈值(DBL_EPSILON
或 FLT_EPSILON
)乘以两个数绝对值的较大值。具体来说,对于 double
类型,比较的公式为:
|p1 - p2| <= qMax(qAbs(p1), qAbs(p2)) * DBL_EPSILON;
对于 float
类型,比较的公式为:
|p1 - p2| <= qMax(qAbs(p1), qAbs(p2)) * FLT_EPSILON;
其中,DBL_EPSILON
是 double
类型的最小精度,FLT_EPSILON
是 float
类型的最小精度。
示例代码:
#include <QCoreApplication>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);double num1 = 0.1 + 0.2;double num2 = 0.3;if (qFuzzyCompare(num1, num2)) {qDebug() << "num1 and num2 are approximately equal.";} else {qDebug() << "num1 and num2 are not approximately equal.";}return a.exec();
}
12.qInf、qIsFinite、qIsInf、qIsNaN
原型:
//返回浮点数正无穷大浮点数的函数
double qInf();
float qInf();//判断浮点数是否是一个有穷的数字
bool qIsFinite(double d);
bool qIsFinite(float f);//判断浮点数是否无穷大
bool qIsInf(double d);
bool qIsInf(float f);//判断浮点数是否是一个数字
bool qIsNaN(double d);
bool qIsNaN(float d);
13.qMax、qMin
原型:
//获取最大值
template <typename T> const T &qMax(const T &a, const T &b);
//获取最小值
template <typename T> const T &qMin(const T &a, const T &b);
14.qRound64、qRound
原型:
qint64 qRound64(double d);
qint64 qRound64(float d);
int qRound(double d);
int qRound(float d);
返回d最接近的四舍五入后的整数结果。
示例如下:
//Adouble valueA = 42949672960.3;double valueB = 42949672960.7;qint64 roundedValueA = qRound64(valueA);// roundedValueA = 42949672960qint64 roundedValueB = qRound64(valueB);// roundedValueB = 42949672961//Bfloat valueA = 42949672960.3;float valueB = 42949672960.7;qint64 roundedValueA = qRound64(valueA);// roundedValueA = 42949672960qint64 roundedValueB = qRound64(valueB);// roundedValueB = 42949672961
15.qVersion
原型:
const char *qVersion();
返回字符串的版本号。
16.q_check_ptr
原型:
template <typename T> T *q_check_ptr(T *p);
用于检查指针是否为 nullptr
。当传入的指针为 nullptr
时,它会触发断言(assertion),从而帮助开发者在调试阶段快速定位空指针相关的问题。
示例如下:
#include <QCoreApplication>
#include <QDebug>void processPointer(int* ptr) {// 使用 q_check_ptr 检查指针是否为空q_check_ptr(ptr);// 如果指针不为空,继续处理if (ptr) {*ptr = 10;qDebug() << "Value of pointer: " << *ptr;}
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);int value = 5;int* validPtr = &value;int* nullPtr = nullptr;// 测试有效指针processPointer(validPtr);// 测试空指针,在调试版本中会触发断言processPointer(nullPtr);return a.exec();
}
17.qCeil、qFloor
原型:
//向上取整,结果总是大于或等于原数
double qCeil(double value);
float qCeil(float value);//向下取整,结果总是小于或等于原数
double qFloor(double value);
float qFloor(float value);
18.qgetenv、qputenv
原型:
//获取环境变量的值
QByteArray qgetenv(const char *varName);//设置环境变量的值
bool qputenv(const char *varName, const QByteArray &value);
示例如下:
#include <QCoreApplication>
#include <QDebug>
#include <QByteArray>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);// 获取 PATH 环境变量的值QByteArray pathValue = qgetenv("PATH");if (!pathValue.isEmpty()) {qDebug() << "The value of PATH environment variable is:" << pathValue;} else {qDebug() << "The PATH environment variable is not set.";}// 获取一个不存在的环境变量的值QByteArray nonExistentValue = qgetenv("NON_EXISTENT_VARIABLE");if (!nonExistentValue.isEmpty()) {qDebug() << "The value of NON_EXISTENT_VARIABLE is:" << nonExistentValue;} else {qDebug() << "The NON_EXISTENT_VARIABLE environment variable is not set.";}return a.exec();
}
19.qtTrId
原型:
QString qtTrId(const char *id, int n = -1);
在 Qt 应用程序里进行国际化操作时,通常会使用 tr()
函数来标记需要翻译的文本。不过,当处理大量文本或者需要动态管理翻译内容时,使用 qtTrId
搭配翻译标识符会更加灵活方便。翻译标识符是一个字符串,它唯一地标识了一段需要翻译的文本,开发者可以借助这个标识符来获取对应的翻译结果。
使用步骤
1)定义翻译标识符:在代码中定义翻译标识符,通常会在 .h
文件或者 .cpp
文件里进行。例如:
// 定义翻译标识符
#define TRANSLATION_ID_HELLO "hello_message"
2)标记翻译文本:在 .ts
文件(Qt 的翻译源文件)里,使用翻译标识符来标记需要翻译的文本。例如:
<context><name>MainWindow</name><message><location filename="mainwindow.cpp" line="10"/><source>hello_message</source><translation>你好!</translation></message>
</context>
3)使用 qtTrId
获取翻译文本:在代码中使用 qtTrId
函数,通过翻译标识符来获取对应的翻译文本。例如:
#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <QWidget>// 定义翻译标识符
#define TRANSLATION_ID_HELLO "hello_message"int main(int argc, char *argv[])
{QApplication a(argc, argv);// 创建一个标签,使用 qtTrId 获取翻译文本QLabel *label = new QLabel(qtTrId(TRANSLATION_ID_HELLO));QVBoxLayout *layout = new QVBoxLayout;layout->addWidget(label);QWidget window;window.setLayout(layout);window.show();return a.exec();
}