前言
取色器在实际工作中经常用到。目前遇到一个场景,点击btn就开始从lable上的图片中取色,然后从图片中获取到想要的颜色后,点击label就结束取色。于是自己写了一个demo
一、效果图
二、源代码
1.UI设计
2.头文件
代码如下:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPixmap>
#include <QImage>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void showColorValue();
protected:
bool eventFilter(QObject *watched, QEvent *event);
private slots:
void on_btn_start_clicked();
private:
Ui::MainWindow *ui;
void InitUI();
QTimer *m_timer = nullptr;
QString m_text = "";
QImage m_img;
};
#endif // MAINWINDOW_H
3.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QScreen>
#include <QDesktopWidget>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
InitUI();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btn_start_clicked()
{
if (!m_timer->isActive())
m_timer->start(100);
}
void MainWindow::InitUI()
{
QImage img("D:/img/python.jpg" );
m_img = img;
ui->lb_pic->setPixmap(QPixmap::fromImage(img));
ui->lb_pic->installEventFilter(this);
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, [=]() { showColorValue(); } );
}
//label捕获鼠标事件
bool MainWindow::eventFilter(QObject * watched, QEvent * event)
{
if(qobject_cast<QLabel*>(watched) == ui->lb_pic && event->type() == QEvent::MouseButtonRelease)
{
if (m_timer->isActive())
m_timer->stop();
return true;
}
return false;
}
//定时器内操作的函数
void MainWindow::showColorValue()
{
m_text.clear();
//获取鼠标x,y坐标
int x = QCursor::pos().x();
int y = QCursor::pos().y();
//获取坐标像素点
QScreen *screen = qApp->primaryScreen();
QPixmap pixmap = screen->grabWindow(0, x, y, 2, 2);
//获取像素点RGB
int red, green, blue;
QImage image = pixmap.toImage();
QColor color = image.pixel(0,0);
red = color.red();
green = color.green();
blue = color.blue();
//int转成16进制的颜色
QString hRed = QString::number(red,16).toUpper();
QString hGreen = QString::number(green,16).toUpper();
QString hBlue = QString::number(blue,16).toUpper();
m_text = QString("鼠标位置 x:%1 y:%2 \t 16进制颜色值 #%3%4%5 \t RGB值 R:%6 G:%7 B:%8").arg(x).arg(y)
.arg(hRed).arg(hGreen).arg(hBlue).arg(red).arg(green).arg(blue);
//显示
ui->lb_result->setText(m_text);
}
三、源码
源码已上传csdn
Qt5实现的简单的取色器
总结
思路是,QLabel获取鼠标按下事件,停止计时器。