Qt是一个跨平台的C++图形用户界面应用程序框架,通过使用Qt,可以快速开发出跨平台的多平台应用程序,包括Windows、Mac OS X、Linux和其他Unix系统。Qt提供了强大的图形操作界面(GUI)程序开发和移植的能力,以及对网络、数据库和其他技术的支持,能够满足多平台应用程序的需求。
可以使用Qt的QPainter类来绘制仪表盘,主要的步骤如下:
示例1如下:
void Widget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
// 绘制外圆
painter.setPen(Qt::NoPen);
painter.setBrush(Qt::white);
painter.drawEllipse(rect());
// 绘制分隔线
int step = 30;
painter.setPen(Qt::black);
for (int i = 0; i <= 360; i += step) {
painter.drawLine(rect().center(), pointOnCircle(rect().center(), rect().width() / 2, i));
}
// 绘制指针
painter.setPen(Qt::NoPen);
painter.setBrush(Qt::red);
painter.drawConvexPolygon(m_pointer, 3);
}
示例2如下:
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
// 设置画笔
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() /2); // 将坐标原点移动到中心点
// 绘制仪表盘背景
int radius = qMin(width(), height()) / 2; // 半径
painter.drawEllipse(-radius, -radius, 2 * radius, 2 * radius);
// 绘制仪表盘指针
painter.rotate(m_value * 360.0 / m_maxValue);
QPen pen;
pen.setWidth(radius / 10);
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawLine(0, 0, 0, -radius);
}
示例3如下:
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
int width = this->width();
int height = this->height();
int side = qMin(width, height);
// 画背景
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width / 2, height / 2);
painter.scale(side / 200.0, side / 200.0);
painter.setPen(Qt::NoPen);
// 画背景
painter.setBrush(Qt::white);
painter.drawEllipse(-100, -100, 200, 200);
// 画刻度线
painter.setPen(QPen(Qt::black, 1));
int n = 12;
for (int i = 0; i < n; ++i) {
painter.drawLine(0, -90, 0, -96);
painter.rotate(360.0 / n);
}
// 画数字
painter.setPen(Qt::black);
painter.setFont(QFont("Arial", 10));
for (int i = 0; i < n; ++i) {
int value = i * 30;
QString str = QString("%1").arg(value);
QRectF textRect(-20, -96, 40, 16);
painter.drawText(textRect, Qt::AlignCenter, str);
painter.rotate(360.0 / n);
}
// 画指针
painter.setBrush(Qt::red);
painter.save();
painter.rotate(m_value);
painter.drawConvexPolygon(m_points, 3);
painter.restore();
}
示例4如下:
// 绘制仪表盘
void Widget::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿
painter.translate(width() / 2, height() / 2); // 坐标系原点移动到界面中心
int side = qMin(width(), height());
painter.scale(side / 200.0, side / 200.0); // 缩放坐标系
// 绘制外圆
painter.setPen(QPen(Qt::black, 3));
painter.setBrush(Qt::white);
painter.drawEllipse(-100, -100, 200, 200);
// 绘制刻度
painter.setPen(QPen(Qt::black, 2));
for (int i = 0; i < 360; ++i) {
if (i % 30 == 0) {
painter.drawLine(0, -90, 0, -80);
painter.drawText(-5, -70, QString::number(i / 30));
} else {
painter.drawLine(0, -95, 0, -80);
}
painter.rotate(1.0); // 旋转坐标系
}
// 绘制指针
painter.setPen(QPen(Qt::red, 2));
painter.drawLine(0, 0, 0, -60);
painter.setPen(QPen(Qt::darkRed, 3));
painter.drawLine(0, 0, 0, -70);
}