代码:
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void paintEvent(QPaintEvent *event) override;
public slots:
void hslideValueChangedSlot(int);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QPen>
#include <QtCore/qmath.h>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->horizontalSlider->setMaximum(300);
ui->horizontalSlider->setMinimum(0);
connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(hslideValueChangedSlot(int)));
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter p(this);
//Qpainter:: translate()
p.translate(this->width()/2,this->height()/2);
p.setPen(Qt::NoPen);
QBrush brush; brush.setColor(QColor(192,192,192)); brush.setStyle(Qt::SolidPattern);
p.setBrush(brush);
//外圆
p.drawEllipse(-200,-200,400,400);
QBrush brush1; brush1.setColor(QColor(0,0,0)); brush1.setStyle(Qt::SolidPattern);
p.setBrush(brush1);
//内圆
p.drawEllipse(-170,-170,340,340);
//直线
p.rotate(ui->horizontalSlider->value());
QPen pen; pen.setColor(QColor(255,255,255)); pen.setWidth(4); pen.setStyle(Qt::SolidLine);
p.setPen(pen);
p.drawLine(0,0,-120,120*sqrt(2));
}
void Widget::hslideValueChangedSlot(int)
{
this->update();
}
运行截图: