## 一、前言
在做很多项目的UI界面的时候,相信绝大部分人都有过抄袭别人的UI界面尤其是颜色的时候,毕竟十个程序员九个没有审美,或者说审美跟一坨屎一样,大家主要的精力以及擅长点都是在写功能实现具体功能上面,这个事情怎么说呢,这确实是程序员的主要职责,但是在大部分的小公司,UI也都是需要程序员自己去搞定的,自己想不出来怎么办,借鉴咯,不知道颜色值怎么办,用颜色拾取器点一下咯。
Qt内置的grabWindow方法,可以指定句柄获取对应的颜色,所以如果要对屏幕取得颜色值的话,传入整个屏幕的句柄即可,屏幕的句柄在Qt中的表示是QApplication::desktop()->winId(),要实时获取怎么办呢,当然最简单的办法就是开个定时器咯,定时器不断调用这个方法,获取屏幕鼠标坐标和颜色值。
## 二、代码思路
void ColorWidget::showColorValue(){ if (!pressed) { return; } int x = QCursor::pos().x(); int y = QCursor::pos().y(); txtPoint->setText(tr("x:%1 y:%2").arg(x).arg(y)); QString strDecimalValue, strHex, strTextColor; int red, green, blue;#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) QPixmap pixmap = QPixmap::grabWindow(QApplication::desktop()->winId(), x, y, 2, 2);#else QScreen *screen = QApplication::primaryScreen(); QPixmap pixmap = screen->grabWindow(QApplication::desktop()->winId(), x, y, 2, 2);#endif if (!pixmap.isNull()) { QImage image = pixmap.toImage(); if (!image.isNull()) { if (image.valid(0, 0)) { QColor color = image.pixel(0, 0); red = color.red(); green = color.green(); blue = color.blue(); QString strRed = tr("%1").arg(red & 0xFF, 2, 16, QChar('0')); QString strGreen = tr("%1").arg(green & 0xFF, 2, 16, QChar('0')); QString strBlue = tr("%1").arg(blue & 0xFF, 2, 16, QChar('0')); strDecimalValue = tr("%1, %2, %3").arg(red).arg(green).arg(blue); strHex = tr("#%1%2%3").arg(strRed.toUpper()).arg(strGreen.toUpper()).arg(strBlue.toUpper()); } } } if (red > 200 && green > 200 && blue > 200) { strTextColor = "10, 10, 10"; } else { strTextColor = "255, 255, 255"; } QString str = tr("background-color: rgb(%1);color: rgb(%2)").arg(strDecimalValue).arg(strTextColor); labColor->setStyleSheet(str); txtRgb->setText(strDecimalValue); txtWeb->setText(strHex);}
## 三、效果图

## 四、开源主页
**以上作品完整源码下载都在开源主页,会持续不断更新作品数量和质量,欢迎各位关注。**
1. 国内站点:[https://gitee.com/feiyangqingyun/QWidgetDemo](https://gitee.com/feiyangqingyun/QWidgetDemo)
2. 国际站点:[https://github.com/feiyangqingyun/QWidgetDemo](https://github.com/feiyangqingyun/QWidgetDemo)
3. 个人主页:[https://blog.csdn.net/feiyangqingyun](https://blog.csdn.net/feiyangqingyun)
4. 知乎主页:[https://www.zhihu.com/people/feiyangqingyun/](https://www.zhihu.com/people/feiyangqingyun/)