【问题标题】:Why QPixmap::scaled() does not work?为什么 QPixmap::scaled() 不起作用?
【发布时间】:2013-07-06 16:04:53
【问题描述】:

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

chesstile.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);
}

chesstile.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

【问题讨论】:

    标签: c++ qt qpixmap


    【解决方案1】:

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

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

    尝试类似:

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

    【讨论】:

    • 谢谢。现在可以了。我不知道为什么没有注意这个细节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2013-03-07
    • 2019-08-06
    相关资源
    最近更新 更多