需求创建 widget 时,设置随机背景色,如图。
主要代码:
- #include <iostream>
- #include <random>
- using namespace std;
- std::default_random_engine e;
- std::uniform_real_distribution<double> random(0,1);
-
- // 获取随机颜色
- QColor color = QColor::fromRgb(int(random(e)*255), int(random(e)*255), int(random(e)*255));
- QString winColor = color.name();
-
- //设置背景色方法一
- ui->signColor->setStyleSheet("QLabel{background-color: "+ winColor + ";border:2px groove #191919;}");
-
- //方法二
- ui->signColor->setStyleSheet("background-color:rgb("+ QString::number(int(random(e)*255)) + "," +
- QString::number(int(random(e)*255)) + "," + QString::number(int(random(e)*255)) + ");");
- //获取 r/g/b 值
-
- QColor color = QColorDialog::getColor(Qt::white, this);
- qDebug() << "颜色选择" << color << color.name();
- QRgb rgb = color.rgb();
-
- qDebug() << "rgb== " << qRed(rgb) << qGreen(rgb) << qBlue(rgb);