Qt QML实现Windows桌面颜色提取器

发布于:2025-04-18 ⋅ 阅读:(69) ⋅ 点赞:(0)

前言

实现一个简单的小工具,使用Qt QML实现Windows桌面颜色提取器,实时显示鼠标移动位置的颜色值,包括十六进制值和RGB值。该功能在实际应用中比较常见,比如截图的时候,鼠标移动就会在鼠标位置实时显示坐标和颜色值,做项目实现UI的时候可能会经常用到这个功能,快速提取设计图的颜色值。

效果图如下:
在这里插入图片描述
代码使用Qt 5.15.2版本实现,QML实现UI交互。
后期可以在此基础上扩展更多的功能,比如鼠标右键的时候,就暂停提取,然后添加一个复制按钮,可以方便复制当前的颜色值,然后直接取用。

正文

实现原理就是移动移动的时候,实时在屏幕鼠标处截取图片然后获取图片上的颜色值。

    QPixmap pixmap = screen->grabWindow(0, screenPos.x(), screenPos.y(), 1, 1);
    
    QImage image = pixmap.toImage();
    if (image.isNull() || image.width() < 1 || image.height() < 1) {
        return; 
    }
    QColor color = QColor(image.pixel(0, 0));
Rectangle {
        anchors.fill: parent
        color: "#f0f0f0"
        border.color: "#cccccc"
        border.width: 1
        radius: 5

        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 10

            Text {
                Layout.alignment: Qt.AlignHCenter
                text: "颜色提取器"
                font.pixelSize: 18
                font.bold: true
            }

            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 50
                color: colorPicker.isActive ? colorPicker.hexColor : "#cccccc"
                border.color: "#999999"
                border.width: 1
                radius: 4

                Text {
                    anchors.centerIn: parent
                    text: colorPicker.isActive ? colorPicker.hexColor : "等待提取颜色..."
                    color: colorPicker.isActive ? (isDarkColor(colorPicker.red, colorPicker.green, colorPicker.blue) ? "white" : "black") : "black"
                    font.pixelSize: 14
                }


            }

            Text {
                Layout.alignment: Qt.AlignHCenter
                text: colorPicker.isActive ? colorPicker.rgbColor : "RGB(0, 0, 0)"
                font.pixelSize: 14
            }

            Button {
                Layout.fillWidth: true
                Layout.preferredHeight: 40
                text: colorPicker.isActive ? "停止提取" : "开始提取"
                onClicked: {
                    if (colorPicker.isActive) {
                        colorPicker.stopPicking()
                    } else {
                        colorPicker.startPicking()
                    }
                }
            }

            Button {
                Layout.fillWidth: true
                Layout.preferredHeight: 30
                text: "退出"
                onClicked: {
                    Qt.quit()
                }
            }
        }
    }

完整Demo下载