最简单的方法是继承 QLabel,添加额外的方法来接受前景/背景像素图,并覆盖 paintEvent 函数。
其他方法可能如下所示:
// literally the same thing as setPixmap but constructed a new function to be clearer
void CustomLabel::setBackground(const QPixmap & pixmap)
{
// will handle sizing the label to the size of the image
// and will additionally handle drawing of the background
this->setPixmap(pixmap);
}
void CustomLabel::setForeground(const QPixmap & pixmap)
{
// create member variable that points to foreground image
this->foreground = pixmap;
}
然后,覆盖paintEvent函数:
void CustomLabel::paintEvent(QPaintEvent * e)
{
// use the base class QLabel paintEvent to draw the background image.
QLabel::paintEvent(e);
// instantiate a local painter
QPainter painter(this);
// draw foreground image over the background
// draws the foreground starting from the top left at point 0,0 of the label.
// You can supply a different offset or source/destination rects to achieve the
// blitting effect you want.
painter.drawPixmap(QPoint(0,0),this->foreground);
}
...然后您可以按如下方式使用标签:
//instantiate a custom label (or whatever you choose to call it)
label = new CustomLabel();
// use the additional methods created as part of your CustomLabel class
label->setBackground(QPixmap("background.png"));
label->setForeground(QPixmap("foreground.png"));
此外,CustomLabel 类可以进一步扩展以接受不止一个背景和前景图像。例如,一个setPixmaps(QVector<QPixmap>)
函数可以存储它传递的图像向量,将标签调整为向量中的第一个图像,然后利用paintEvent函数绘制所有传递给它的图像。
请记住,前景图像的大小应小于或等于背景图像的大小,以免前景图像被裁剪。(因为 QPainter 不会管理调整其绘画的小部件的大小。)
编辑:
现在我只想使用在背景图像(1366x768)上移动的“Qpainter.drawImage”用新图像(尺寸 30x30)覆盖背景。这就像在屏幕上移动鼠标指针,其中屏幕是背景形式(Qlabel 上的 .png 图像),鼠标指针是使用“Qpainter.drawImage”动态绘制的新图像
为此,您可以对 setForeground 函数进行简单的编辑/重载,并像这样修改 paintEvent 函数:
void CustomLabel::setForeground(const QPixmap & pixmap, const QPointF & offset)
{
// create member variable that points to foreground image
this->foreground = pixmap;
// establish the offset from the top left corner of the background image
// to draw the top left corner of the foreground image.
this->foregroundOffset = offset;
}
void CustomLabel::paintEvent(QPaintEvent * e)
{
// use the base class QLabel paintEvent to draw the background image.
QLabel::paintEvent(e);
// instantiate a local painter
QPainter painter(this);
// draw foreground image over the background using given offset
painter.drawPixmap(this->foregroundOffset,this->foreground);
}