【问题标题】:QT QGraphicsScene Drawing ArcQT QGraphicsScene 绘制圆弧
【发布时间】:2013-01-11 13:25:34
【问题描述】:

我有一个关于在场景中绘制特定弧线的问题。我有关于弧的这些信息:

起始坐标, 起始角度, 端角 , 半径。

但我不能有效地将它们与QPainter 一起使用。实际上我尝试QPainterPath 使用形状在QGraphicsSceneaddPath("") 上显示,但我无法正确使用功能。我的问题是关于如何使用这些信息来绘制弧线以及如何在我的图形场景中显示它。

【问题讨论】:

    标签: c++ qt qgraphicsscene qpainter


    【解决方案1】:

    您可以使用QGraphicsEllipseItemQGraphicsScene 添加椭圆、圆和线段/弧线。

    试试

    QGraphicsEllipseItem* item = new QGraphicsEllipseItem(x, y, width, height);
    item->setStartAngle(startAngle);
    item->setSpanAngle(endAngle - startAngle);
    scene->addItem(item);
    

    很遗憾,QGraphicsEllipseItem 只支持QPainter::drawEllipse()QPainter::drawPie()——后者可用于绘制弧线,但有副作用,即从弧线的起点和终点到中心总是有一条线。

    如果你需要一个真正的弧线,你可以例如子类QGraphicsEllipseItem 并覆盖paint() 方法:

    class QGraphicsArcItem : public QGraphicsEllipseItem {
    public:
        QGraphicsArcItem ( qreal x, qreal y, qreal width, qreal height, QGraphicsItem * parent = 0 ) :
            QGraphicsEllipseItem(x, y, width, height, parent) {
        }
    
    protected:
        void paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {
            painter->setPen(pen());
            painter->setBrush(brush());
            painter->drawArc(rect(), startAngle(), spanAngle());
    
    //        if (option->state & QStyle::State_Selected)
    //            qt_graphicsItem_highlightSelected(this, painter, option);
        }
    };
    

    然后您仍然需要处理项目突出显示,不幸的是qt_graphicsItem_highlightSelected 是 Qt 库中定义的静态函数。

    【讨论】: