Написание виджета с использованием 2 изображений в Qt
Я пишу виджет датчика, используя 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);
}
этот код вращает мою иглу правильно, но ее положение не является правильным. Кто-нибудь может мне помочь? Благодарю.
1 ответ
Скорее всего, это будет зависеть от ваших изображений и размера виджета. Я попробовал ваш код, и мне кажется, что QTransform().translate()
ничего не делает в QPixmap
, Я пытался дать экстремальные значения для translate()
и удалил rotate()
- изображение не двигается.
У меня уже есть своя собственная реализация для датчика. Это с преобразованием художника вместо изображения. Мои изображения имеют размеры:
Gauge Background: 252x252 (есть некоторые внешние эффекты размытия по границам круга, делающие фоновое изображение больше, чем кажется)
Игла: 7х72 (размеры изображения обвивают границы самой иглы)
Центр вращения иглы (относительно фона): 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();
}