我是靠谱客的博主 快乐羽毛,这篇文章主要介绍qt 自定义颜色选择器,现在分享给大家,希望可以做个参考。

在右边选择颜色,左侧的QLable  背景色会跟着变化 

核心难点:

    通过鼠标点击的坐标, 获取点击的颜色值。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
void MyColorWidget::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); rectColor = QRect(0,0,this->width(),this->height()); QLinearGradient linearGradient(0,0,0,this->height()); linearGradient.setColorAt(0, Qt::red); linearGradient.setColorAt(0.2, Qt::yellow); linearGradient.setColorAt(0.4, Qt::green); linearGradient.setColorAt(0.6, Qt::blue); linearGradient.setColorAt(0.8, Qt::black); linearGradient.setColorAt(1, Qt::white); painter.setBrush(QBrush(linearGradient)); painter.setPen(QPen(Qt::black,1)); painter.drawRect(rectColor); } void MyColorWidget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { this->setFocus(); QPoint point = event->pos(); getPointColor(point); emit choicesColor(myColor); } } void MyColorWidget::mouseMoveEvent(QMouseEvent *event) { if(Qt::LeftButton == (event->buttons() & Qt::LeftButton)) { QPoint point = event->pos(); getPointColor(point); emit choicesColor(myColor); } } void MyColorWidget::getPointColor(const QPoint &point) { // 通过抓屏,获取某一点的颜色 if(rectColor.contains(point)) { QPoint deskPoint = mapToGlobal(point); // 转换为桌面坐标 // 抓屏,截取一个像素的图片 QScreen *m_screen = this->window()->windowHandle()->screen(); QPixmap pixmap = m_screen->grabWindow(QApplication::desktop()->winId(), deskPoint.x(), deskPoint.y(), 1, 1); if (!pixmap.isNull()) { QImage image = pixmap.toImage(); if (!image.isNull()) { myColor = image.pixel(0, 0); int m_red = myColor.red(); int m_green = myColor.green(); int m_blue = myColor.blue(); rgbStr = QString("%1, %2, %3").arg(m_red).arg(m_green).arg(m_blue); update(); } delete ℑ } delete &pixmap; } }

最后

以上就是快乐羽毛最近收集整理的关于qt 自定义颜色选择器的全部内容,更多相关qt内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部