QT中颜色选择器QColorDialog的重新实现

重新实现的颜色选择器如下图所示:

QT中颜色选择器QColorDialog的重新实现_第1张图片QT中颜色选择器QColorDialog的重新实现_第2张图片


颜色的渐变都是通过拉渐变或者是直接在paintevent中画出来的,根据hsv和rgb两种颜色类型之间的转化来实现。

重载QSlider来实现颜色条花了不少时间,经过别人指点后才恍然大悟,主要还是对这些类的用法和类的实现原理不熟悉造成的,下来得好好的熟悉下。

重载QSlider实现颜色滚动条的代码如下:

    QPainter painter(this);

    if(this->orientation() == Qt::Horizontal)
    {
        const int offset = 5;
        QRect rect = this->rect();
        rect.setHeight(rect.height() - 5);
        QRect sliderRect = rect.adjusted(offset,0,-offset,-rect.height()/2);

        painter.setPen(QPen(Qt::black, 0.5));
        painter.setBrush(back);
        painter.drawRect(sliderRect);
        painter.setBrush(gradient());
        painter.drawRect(sliderRect);

        const double k = (double)(value() - minimum()) / (maximum()-minimum());
        int x = (int)((rect.width()-2*offset) * k) + offset;
        QPoint tickPts[] = {
            QPoint(x,sliderRect.bottom()+1),
            QPoint(x-offset,rect.bottom()-1),
            QPoint(x+offset,rect.bottom()-1),
        };
        painter.setBrush(Qt::white);
        painter.drawPolygon(tickPts,3);
        return;
    }

    this->setFixedWidth(25);
    const int offset = 5;
    QRect rect = this->rect();
    QRect sliderRect = QRect(rect.left()+offset, rect.top()+offset,
                             rect.right()-2*offset,rect.bottom()-2*offset);
    const double k = (double)(value() - minimum()) / (maximum()-minimum());
    int y = (int)((rect.height()-2*offset) * (1-k)) + offset;
    QPoint tickTop[] = {
        QPoint(sliderRect.left(), y),
        QPoint(rect.left(), y - offset),
        QPoint(rect.left(), y + offset)
    };
    painter.setPen(QPen(Qt::black, 0.5));
    painter.drawPolygon(tickTop, 3);

    painter.setBrush(back);
    painter.drawRect(sliderRect);
    painter.setBrush(gradient());
    painter.drawRect(sliderRect);

    QPoint tickPts[] = {
        QPoint(sliderRect.right()+1, y),
        QPoint(rect.right(), y - offset),
        QPoint(rect.right(), y + offset)
    };

    painter.setBrush(Qt::white);
    painter.drawPolygon(tickPts,3);

详细项目源码已经上传了,需要的可以去瞅瞅,版本QT5.3.

GitHub下载:点击打开链接

CSDN下载:点击打开链接




你可能感兴趣的:(Qt)