• qt 自定义颜色选择器


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

    核心难点:

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

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

  • 相关阅读:
    通过R Studio用Markdown写Beamer
    校园论坛(Java)—— 数据报表模块
    2、IoC 浅识
    如何启用启用WordPress调试模式
    利用python爬取上证指数股吧评论并保存到mongodb数据库
    面试官:MyBatis 插件用途和底层原理
    2023第五届中国(济南)国际中医药产业展览会(CJTCM)
    Fastjson反序列化漏洞
    JAVA-链式编程
    【小记录】jupyter notebook新版本
  • 原文地址:https://blog.csdn.net/chen1231985111/article/details/126584479