为什么QPixmap::scaled()不起作用

Why QPixmap::scaled() does not work?

本文关键字:不起作用 scaled QPixmap 为什么      更新时间:2023-10-16

我正在使用QPixmap和QPainter编写简单的应用程序。在我的程序中,我需要加载一些图像并调整它们的大小。我使用了QPixmap::scaled(),但图像没有缩放。我做错了什么?这是我的代码:

棋盘格.cpp

#include "chesstile.h"
ChessTile::ChessTile(QWidget *parent) :
    QLabel(parent)
{
}
void ChessTile::paintEvent(QPaintEvent *)
{
    const QString &fileName = "images/white_king.png";
    QPixmap bgPixmap(fileName);
    bgPixmap.scaled(QSize(64, 64));
    QPainter painter(this);
    painter.drawPixmap(0, 0, bgPixmap);
}

棋子.h

#ifndef CHESSTILE_H
#define CHESSTILE_H
#include <QLabel>
#include <QString>
#include <QPainter>
#include <QPixmap>
#include <QSize>
class ChessTile : public QLabel
{
    Q_OBJECT
public:
    ChessTile(QString fileName,
              QString tileColor,
              QWidget *parent = 0);
    void paintEvent(QPaintEvent *);
private:
signals:
public slots:
};
#endif // CHESSTILE_H

您将从文档中注意到QPixmap::scaled成员函数是const,即它不会更改对象本身。

缩放后的对象通过该方法返回,它不会更改原始像素图。

试试类似的东西:

QPixmap bgPixmap(fileName);
QPixmap scaled = bgPixmap.scaled(QSize(64, 64));
QPainter painter(this);
painter.drawPixmap(0, 0, scaled)