Qt实用函数(宏)

小编:啊南 388阅读 2021.01.18

下列函数或宏均来自Qt的qglobal.h头文件。

  • 求绝对值
template 
Q_DECL_CONSTEXPR inline T qAbs(const T &t) { return t >= 0 ? t : -t; }
  • 舍入到最接近的整数,如:0.5 ==> 1,-0.5 => 0
Q_DECL_CONSTEXPR inline int qRound(double d)
{ return d >= 0.0 ? int(d + 0.5) : int(d - double(int(d-1)) + 0.5) + int(d-1); }
Q_DECL_CONSTEXPR inline int qRound(float d)
{ return d >= 0.0f ? int(d + 0.5f) : int(d - float(int(d-1)) + 0.5f) + int(d-1); }

Q_DECL_CONSTEXPR inline qint64 qRound64(double d)
{ return d >= 0.0 ? qint64(d + 0.5) : qint64(d - double(qint64(d-1)) + 0.5) + qint64(d-1); }
Q_DECL_CONSTEXPR inline qint64 qRound64(float d)
{ return d >= 0.0f ? qint64(d + 0.5f) : qint64(d - float(qint64(d-1)) + 0.5f) + qint64(d-1); }
  • 求最值
template 
Q_DECL_CONSTEXPR inline const T &qMin(const T &a, const T &b) { return (a < b) ? a : b; }
template 
Q_DECL_CONSTEXPR inline const T &qMax(const T &a, const T &b) { return (a < b) ? b : a; }
  • 求中间值
template 
Q_DECL_CONSTEXPR inline const T &qBound(const T &min, const T &val, const T &max)
{ return qMax(min, qMin(max, val)); }
  • 对宏参数字符串化
#define QT_STRINGIFY2(x) #x
#define QT_STRINGIFY(x) QT_STRINGIFY2(x)
  • 避免"未使用的参数"编译警告
#define Q_UNUSED(x) (void)x;
  • 实现禁止类复制
#define Q_DISABLE_COPY(Class)     Class(const Class &) Q_DECL_EQ_DELETE;    Class &operator=(const Class &) Q_DECL_EQ_DELETE;
  • 设置某个环境变量
Q_CORE_EXPORT bool qputenv(const char *varName, const QByteArray& value);
  • 获取某个环境变量
Q_CORE_EXPORT QByteArray qgetenv(const char *varName);
  • 随机数生成
Q_CORE_EXPORT void qsrand(uint seed);
Q_CORE_EXPORT int qrand();
  • 相当于while(1)
#define Q_FOREVER for(;;)
  • D指针与Q指针,主要用于隐藏数据和二进制兼容实现。
#define Q_D(Class) Class##Private * const d = d_func()
#define Q_Q(Class) Class * const q = q_func()
关联标签: