先上图:
平常虽然也可以用截图软件Snipaste来获取颜色值,但这软件是用Qt来写的就想着自己也来写个简单的颜色获取。
直接上代码
#include "widget.h"
#include "ui_widget.h"
//#include <windows.h>
//#include <iostream>
#include<QApplication>
#include<QDesktopWidget>
#include<QPixmap>
#include <QScreen>
//#include<QDebug>
#include<QWindow>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowIcon(QIcon(":/color_wheel_48px_25834_easyicon.net.png"));
// setWindowFlag(Qt::Dialog,true);
// setWindowFlag(Qt::WindowStaysOnTopHint,true);
setWindowFlags(Qt::WindowStaysOnTopHint);
resize(280,100);
setMinimumSize(280,100);
setMaximumSize(280,100);
setWindowTitle("鼠标下颜色拾取");
QColor color(255, 255, 255);//("#ffffff");白色
ui->showColorlbl->setStyleSheet(QString("background-color: rgb(%1, %2, %3);")
.arg(color.red()).arg(color.green()).arg(color.blue()));
ui->webV->setText(color.name());
ui->rgbV->setText(QString("(%1, %2, %3)")
.arg(color.red()).arg(color.green()).arg(color.blue()));
// setMouseTracking(true);
// ui->posV->setMouseTracking(true);
// POINT point;
// GetCursorPos(&point);
std::cout<<point<<std::endl;
// qDebug() << point.x << point.y;
timerID = this->startTimer(80);
ui->pushButton->lower();
ui->pushButton->hide();
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == timerID) {
// POINT point;
// GetCursorPos(&point);
// ui->posV->setText(QString("(x:%1, y:%2)").arg(point.x).arg(point.y));
// qDebug() << point.x << point.y;
//停止时间
// static int count = 0;
// count++;
// if (count == 100)
// this->killTimer(timerID);
// if (prePoint != QCursor::pos()) {
//获取数据
// prePoint = QCursor::pos();
int x = QCursor::pos().x();//prePoint.x();
int y = QCursor::pos().y();//prePoint.y();
ui->posV->setText(QString("(x:%1, y:%2)").arg(x).arg(y));
QWindow *window = windowHandle();
QScreen *myScreen = window->screen();
// QPixmap pixmap = QPixmap::grabWindow(QApplication::desktop()->winId()
// ,prePoint.x(),prePoint.y(),20,20);
// QPixmap pixmap = myScreen->grabWindow(QApplication::desktop()->winId()
// ,prePoint.x()-40,prePoint.y()-40,80,80);
QPixmap pixmap = myScreen->grabWindow(QApplication::desktop()->winId(),x-2,y-2,4,4);
QColor color = pixmap.toImage().pixel(2,2);
//更新数据
// QColor color(qrand()%255, qrand()%255, qrand()%255);//("#ffffff");白色
ui->showColorlbl->setStyleSheet(QString("background-color: rgb(%1, %2, %3);")
.arg(color.red()).arg(color.green()).arg(color.blue()));
ui->webV->setText(color.name());
ui->rgbV->setText(QString("(%1, %2, %3)").arg(color.red()).arg(color.green()).arg(color.blue()));
// }
} else {
e->accept();
}
}
void Widget::on_pushButton_clicked()
{
timerID = this->startTimer(150);
}
主要是用定时器来获取鼠标位置,再识别pos下的颜色值,是个简单的小程序,以上。