获取颜色对应的字符串

16进制字符串和颜色之间的转换

Posted by 雯饰太一 on May 28, 2023

获取颜色对应的字符串

获取颜色的字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
QString GetQColorStr(const QColor& t_color)
{
	int c_red = t_color.red();
	int c_green = t_color.green();
	int c_blue = t_color.blue();
	int c_alpha = t_color.alpha();

	QString color_str;
	color_str = "0x" + QString("%1%2%3%4").
		arg(t_color.alpha(), 2, 16, QLatin1Char('0'))
		.arg(t_color.red(), 2, 16, QLatin1Char('0'))
		.arg(t_color.green(), 2, 16, QLatin1Char('0'))
		.arg(t_color.blue(), 2, 16, QLatin1Char('0'));

	return color_str;
}

或者使用QT自带的方法获取ARGB字符串,以下是一个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <QColor>
#include <QDebug>

int main() {
    QColor color(Qt::red);  // 创建一个红色 QColor 对象

    // 获取 ARGB 字符串表示颜色的值
    QString argbString = color.name(QColor::HexArgb);

    qDebug() << argbString;  // 打印 ARGB 字符串

    return 0;
}

根据字符串获取颜色

1
2
3
4
5
6
7
8
9
QColor GetQClrByStr(QString t_color)
{
	unsigned int argb = t_color.toUInt(bool(), 16);
	return QColor(
		(argb & 0x00FF0000) >> 16,
		(argb & 0x0000FF00) >> 8,
		(argb & 0x000000FF),
		(argb & 0xFF000000) >> 24);
}