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

核心难点:
通过鼠标点击的坐标, 获取点击的颜色值。
- 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;
- }
- }