【问题标题】:How to create one side rounded and other side flat rectangle using QPainter?如何使用 QPainter 创建一侧圆角和另一侧扁平矩形?
【发布时间】:2018-06-28 13:08:16
【问题描述】:

我想使用 QPainter 实现这样的目标

我尝试在 QPainter 中并排使用 2 个圆角矩形,但无法实现上图。

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    QRectF leftRect= QRectF(0, 0, 300, 150);
    QRectF rightRect= QRectF(300, 0, 300, 150);
    painter.fillRect(leftRect, QColor("black");
    painter.drawRoundedRect(leftRect,15,35);
    painter.setPen(QPen("white"));
    painter.setPen(QPen("black"));
    painter.fillRect(rightRect, QColor("white");
    painter.drawRoundedRect(rightRect,15,35);    

这是我尝试并得到了这个

我用 QPainterPath 试过这个

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QRectF leftRect= QRectF(0, 0, 300, 150);
QRectF rightRect= QRectF(300, 0, 300, 150);
QPainterPath path;
path.setFillRule(Qt::WindingFill);
path.addRoundedRect(leftRect, 15, 35);
QPen pen(Qt::white, 1);
painter.setPen(pen);
painter.fillPath(path, Qt::black);
painter.drawPath(path);

QPainterPath path2;
path2.setFillRule(Qt::WindingFill);
QPen pen1(Qt::black, 1);
painter.setPen(pen1);
path2.addRoundedRect(rightRect, 15, 35);

painter.fillPath(path2, Qt::white);
painter.drawPath(path2);  

得到了这个:

【问题讨论】:

  • 两边需要圆角还是半圆?
  • 是的,它是两个并排的矩形。一侧是圆形的,另一侧是平的

标签: qt qtwidgets


【解决方案1】:

Qt 在这方面提供的最好的方法是分开的 x 和 y 圆角半径。因此,开箱即用的任何东西都无法满足您的需求。

似乎要获得该几何图形的方法是使用QPainterPath 将形状由几个子组件组成,在您的情况下,半径为圆弧,其余部分为 3 条线。

您应该能够翻译和镜像画家以绘制另一面。所以你填充并勾勒左侧,然后翻转画家并勾勒右侧。

此外,如果您正在绘制进度条之类的东西,还有另一种做法。您将绘制一个常规圆角矩形并将其用作蒙版,然后您可以通过绘制一个常规矩形来填充您想要的数量,该矩形将被蒙版裁剪成所需的形状。

好的,您似乎需要一些额外的帮助,这里有一些您可以调整的工作代码:

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    QPainterPath path;

    // compose the "half"
    path.moveTo(20, 0);
    path.lineTo(100, 0);
    path.lineTo(100, 40);
    path.lineTo(20, 40);
    path.arcTo(0, 0, 40, 40, -90, -180);

    // draw black half
    painter.setBrush(Qt::black);
    painter.setPen(QPen(Qt::black, 1));
    painter.drawPath(path);

    // mirror and reposition the painter
    QTransform mirror(-1, 0, 0, 0, 1, 0, 0, 0, 1);
    painter.setTransform(mirror);
    painter.translate(-200, 0);

    // draw white half
    painter.setBrush(Qt::white);
    painter.drawPath(path);

【讨论】:

  • 您能否在这样做时显示示例工作代码。因为我尝试使用 QPainterPath。它没有正确渲染
  • 在问题中发布您的代码和结果,看看出了什么问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
相关资源
最近更新 更多