我正在编写一个使用QT的量表小部件,它由2个独立的图像构成,一个作为背景,另一个作为针。我重新实现paintEvent函数如下:
void myGaugeWidget::paintEvent(QPaintEvent *pe)
{
QPainter painter(this);
QPixmap bkgImage(bkgImgPath);
painter.drawPixmap(0, 0, width(), height(), bkgImage);
const double thetaDeg = 30.0;
QPixmap needle(needles[i].imgPath);
int needleWidth = 200;
int needleHeight = 200;
int anchorX = 20;
int anchorY = 30;
const int centerX = width()/2;
const int centerY = height()/2;
QTransform rm = QTransform().translate(-anchorX,- anchorY).rotate(thetaDeg).translate(centerX,centerY);
needle = needle.transformed(rm);
painter.drawPixmap(0,0, needle);
}
此代码正确旋转我的针,但其位置不正确。 有谁能够帮我? 感谢。
答案 0 :(得分:1)
这很可能取决于您的图片和小部件大小。我已经尝试过您的代码,在我看来QTransform().translate()
没有在QPixmap
中执行任何操作。我试图为translate()
提供极值并删除rotate()
- 图片不会移动。
我已经有了自己的仪表实现。这是画家转换而不是图像。我的图片有尺寸:
Gauge Background:252x252(圆形边界周围有一些外部模糊效果,使背景图像比看起来更大)
针:7x72(图像尺寸环绕针本身的边界)
针刺中心(相对于背景):126,126(背景大小除以2)
针图像指向上方
对于此设置,我的paintEvent()
有一些解释:
void myGaugeWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
//draw the background which is same size as the widget.
painter.drawPixmap(0, 0, bg.width(), bg.height(), bg);
//Calculate the angle of rotation.
//The gauge I am using has a cutout angle of 120 degrees at the bottom (symmetric)
float needleAngle = -120/*offset for start rotation*/ + ((value-minValue)*240/*total sweep of the gauge*//(maxValue-minValue));
painter.save();
//translate the painter to the roation center and then perform the rotation
painter.translate(126, 126);
painter.rotate(needleAngle);
//translate the rotated canvas to adjust for the height of the needle.
//If you don't do this, your needle's tip will be at the rotation center
painter.translate(0, -72);
//draw the needle and adjust for the width with the x value
painter.drawPixmap(-needle.width()/2, 0, needle.width(), needle.height(), needle);
painter.restore();
}