Convert between QColor and QString

QColor needs to be used in the project today, but the Qt type is not supported in another compilation environment, or QColor cannot be used for other reasons, then it is the best practice to switch to QString at this time, because strings are supported in any language , you only need to extract the rgb of QColor and convert it into a string, then it can be compatible with any subsequent operations.

Without further ado, let's go to the code:

	 //函数的声明
     //字符串转QColor ,如:"255,0,0"/"red" to QColor(Qt::red)
     QColor stringToColor(QString colorStr);
     //QColor转字符串:,如:QColor(Qt::red) to "255,0,0"
     QString colorTostring(QColor color);



	//函数的实现
	QColor stringToColor(QString colorStr)
{
    
    
    QColor color;
    QStringList rgb=colorStr.split(',');
    if(rgb.size()==3){
    
    
        int r=rgb.at(0).toInt();
        int g=rgb.at(1).toInt();
        int b=rgb.at(2).toInt();
        color.setRgb(r,g,b);
    }
    else
        color.setNamedColor(colorStr);

    return color;
}

QString colorTostring(QColor color)
{
    
    
    QString str = "";
    str = QString::number(color.red())+","+QString::number(color.green())+","+QString::number(color.blue());
    return str;
}


Guess you like

Origin blog.csdn.net/weixin_44650358/article/details/127301187