代码之家  ›  专栏  ›  技术社区  ›  KelvinS Karel Petranek

如何创建具有三角形形状的QWidget?

  •  3
  • KelvinS Karel Petranek  · 技术社区  · 8 年前

    如何创建 QWidget 用三角形?

    它需要是一个 QWidget 因为它将包含在另一个小部件中,必须是可点击的,并将执行一些动画(但在这第一次我只需要创建三角形形状)。

    类似这样:

    enter image description here

    我使用的是Qt 5.3

    1 回复  |  直到 8 年前
        1
  •  3
  •   StPiere    8 年前

    这里有一个例子。希望有帮助。

    小装置。h:

    #ifndef WIDGET_H
    #define WIDGET_H
    
    #include <QWidget>
    #include <QPainterPath>
    #include <QPoint>
    #include <QVector>
    
    class Widget : public QWidget
    {
      Q_OBJECT
    
    public:
      Widget(QWidget *parent = 0);
      ~Widget();
    
    protected:
      void paintEvent(QPaintEvent *event) override;
    
    private:
      QPainterPath getPath() const;
      QRegion getRegion() const;
    
    private:
      int width = 100;
      int height = 100;
      QVector<QPoint> points;
    };
    
    #endif // WIDGET_H
    

    小装置。cpp:

    #include "widget.h"
    #include <QPainter>
    #include <QPoint>
    #include <QPainterPath>
    #include <QBrush>
    #include <QPolygon>
    #include <QVector>
    
    Widget::Widget(QWidget *parent)
      : QWidget(parent),
        points(3)
    {
        points[0] = QPoint(20, 20);
        points[1] = QPoint(80, 20);
        points[2] = QPoint(50, 80);
    
        setFixedSize(width, height);   
        setMask(getRegion());
    }
    
    Widget::~Widget()
    {
    
    }
    
    QPainterPath Widget::getPath() const
    {
        QPainterPath path;
        path.moveTo(points[0]);
        path.lineTo(points[1]);
        path.lineTo(points[2]);
        path.lineTo(points[0]);
    
        return path;
    }
    
    QRegion Widget::getRegion() const
    {
      return QRegion(QPolygon(points));
    }
    
    void Widget::paintEvent(QPaintEvent *event)
    {
        Q_UNUSED(event);
    
        QPainterPath path = getPath();
    
        QPainter painter(this);
        painter.setPen(Qt::NoPen);
        painter.fillPath(path, QBrush(Qt::black));
    }