c++ - Qt中如何按区域填充不同颜色段的圆角矩形?

标签 c++ qt

我是 Qt 的新手,我尝试在网上寻找示例和文档,但找不到任何东西。我想要这样的东西:

enter image description here

我使用 QLinearGradient 尝试过,但它并不是我想要的。我想要纯色。 这是我尝试过的:

void drawBackground ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const {
    QLinearGradient linearGrad(QPointF(option.rect.x(), 0), QPointF(option.rect.x() + option.rect.width(), 0));

    int total = index.data(StatisticsModel::TotalCount).toInt();
    linearGrad.setColorAt(0.0, QColor(255, 255, 255, 0));

    int sum = 0;
    for (int i = 7; i >= 1; i--) {
        int count = index.data(StatisticsModel::Grade0 + i).toInt();

        if (count) {
            sum += count;
            linearGrad.setColorAt(1.0-((double)(total-sum))/total, Prefs::gradeColor(i));

        }
    }


    QRect rect(option.rect);
    rect.adjust(1, 1, -1, -1);

    QPainterPath path;
    path.addRoundedRect( rect, 2.0, 2.0 );
    painter->setBrush(QBrush(linearGrad));
    painter->drawPath(path);
}

如有任何帮助,我们将不胜感激。

最佳答案

好吧,像这样为圆角矩形着色的最佳方法我想是为其创建 QPainterPath 然后构造应该具有指定颜色的普通矩形,将它们与初始圆角矩形相交 QPainterPath 使用函数 QPainterPath::intersected 绘制它们,选择相应的纯色画笔并使用函数 drawPath

关于c++ - Qt中如何按区域填充不同颜色段的圆角矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512316/

相关文章:

c++ - 在linux中通过C++(或python)访问多个键盘输入

c++ - 使用 DirectShow 预览网络摄像头

c++ - Qt c++ 聚合 'std::stringstream ss' 类型不完整,无法定义

c++ - qt中如何实现代码补全

qt - 在 RDP 下运行 QML 应用程序时出现 OpenGL 问题

multithreading - 用互斥锁同步线程

c++ - 如何改进链表搜索。 C++

c++ - 带有枚举的结构的 C++ 复制构造函数的签名

c++ - Rcpp 中没有调用 'as' 的匹配函数

c++ - 继承和 Qt 信号