QWidget获取窗口某点的颜色

从 QColorDialog 的源码中翻出来并整理了一下:

        QScreen *screen = QGuiApplication::screenAt(pressPos);
        if (!screen)
            screen = QGuiApplication::primaryScreen();
        auto gpos = mapToGlobal(pressPos);
        const QPixmap pixmap2 = screen->grabWindow(0, gpos.x(), gpos.y(), 1, 1);
        const QImage i = pixmap2.toImage();
        QColor color = i.pixel(0, 0);
//-------------------------------------------------------------------------------------
        int red = color.red();
        int green = color.green();
        int blue = color.blue();
        QString strDecimalValue = QString("%1, %2, %3").arg(red).arg(green).arg(blue);
        QString strHex = QString("#%1%2%3").arg(QString("%1").arg(red&0xFF,2,16,QLatin1Char('0')).toUpper())    //red&0xFF 数字转成16进制
                                           .arg(QString("%1").arg(green&0xFF,2,16,QLatin1Char('0')).toUpper())
                                           .arg(QString("%1").arg(blue&0xFF,2,16,QLatin1Char('0')).toUpper());

猜你喜欢

转载自blog.csdn.net/kenfan1647/article/details/121154941