前言
思路:首先需要获取到鼠标的x和y坐标点,然后获取鼠标坐标点的像素点。将像素点的rgb分离出来显示。最后label上显示这个像素点的RGB
如果想要实时的显示这些数据的话,使用的是定时器一直调用函数showColorValue就行了
核心代码:
//获取桌面x,y坐标点宽度1,高度1的像素
QWindow window;
QPixmap pixmap = window.screen()->grabWindow(QApplication::desktop()->winId(),x,y,1,1);
效果展示
代码
//需要添加的头文件
#include <QPixmap>
#include <QImage>
#include <QApplication>
#include <QWindow>
#include <QScreen>
#include <QDesktopWidget>
//定时器内操作的函数
void MainWindow::showColorValue()
{
//获取鼠标x,y坐标
int x = QCursor::pos().x();
int y = QCursor::pos().y();
//输出坐标
ui->lineEditCoordinate->setText(tr("x:%1 y:%2").arg(x).arg(y));
//获取坐标像素点
QWindow window;
QPixmap pixmap = window.screen()->grabWindow(QApplication::desktop()->winId(),x,y,1,1);
//获取像素点RGB
int red, green, blue;
if(!pixmap.isNull())
{
QImage image = pixmap.toImage();
if(!image.isNull())
{
QColor color = image.pixel(0,0);
red = color.red();
green = color.green();
blue = color.blue();
//输出16进制的颜色
QString hRed = QString::number(red,16).toUpper();
QString hGreen = QString::number(green,16).toUpper();
QString hBlue = QString::number(blue,16).toUpper();
ui->lineEditHex->setText(tr("#%1%2%3").arg(hRed).arg(hGreen).arg(hBlue));
//输出RGB
ui->lineEditRGB->setText(tr("R:%1 G:%2 B:%3").arg(red).arg(green).arg(blue));
//设置label标签的颜色显示
int width =ui->labelColorDisplay->width();
int height = ui->labelColorDisplay->height();
QPixmap labelPix(width,height);
labelPix.fill(color);
ui->labelColorDisplay->setPixmap(labelPix);
}
}
}