是否可以为 QPixmap 派生类嵌入缩放方法?

Can I embed the scaled method for a QPixmap derived class?

本文关键字:缩放 方法 派生 QPixmap 是否      更新时间:2023-10-16

我希望每个QPixmap派生对象在创建时具有所需的大小。假设我有这个虚构的类:

#pragma once
#include <QPixmap>
#include <QString>
class MyPixmap : public QPixmap
{
public:
enum class Size { icon, veryVerySmall, medium, large };
static int toInt(Size size);
MyPixmap (QString fileName, Size size);
const QString& getPath();
private:
QString m_fileName; //
Size m_size;
};
#include "MyPixmap.h"
#include "MyGraphicsScene.h"
int MyPixmap::toInt(Size size)
{
switch (size)
{
case MyPixmap::Size::icon:
return 20;
case MyPixmap::Size::veryVerySmall:
return MyGraphicsScene::size / 20;
case MyPixmap::Size::medium:
return MyGraphicsScene::size / 32;
case MyPixmap::Size::large:
return MyGraphicsScene::size / 40;
default:
throw std::exception{ "Unreachable code reached" };
}
}
MyPixmap::MyPixmap(QString fileName, Size /* size*/)
:
m_fileName{ fileName }
{
load("PATH/TO/FOLDER/" + fileName + ".png");
// scaled(size, size);
}
const QString& MyPixmap::getPath()
{
return m_piece;
}

所以我可以执行以下代码:

#include "MyPixmap.h"
int main()
{
MyPixmap myPixmap{ "Butterfly", MyPixmap::Size::veryVerySmall };
// pass myPixmap to various functions and objects
return 0;
}

在构造函数内部缩放将不起作用,因为scaled是一个static函数。或者,我可以重载QPixamp scaled(),如下所示:

QPixmap PiecePixmap::scaled()
{
int intSize{ toInt(m_size) };
return scaled(intSize, intSize);
}

但是,我仍然没有使用实际的MyPixmap对象。

是否可以在类本身内部缩放像素图,或者重载scaled我建议的最佳方法是强制某个片段具有内部硬编码大小?

注意:我大量编辑了这篇文章,所以要查看大富翁示例,请查看编辑历史记录。当前的问题代码尚未经过测试,因为它仅用于演示目的。

正如Igor Tandetnik所说,可以通过调用scaled方法并将其返回值传递给复制构造函数来创建立即缩放的 pixmap,如下所示:

MyPixmap::MyPixmap(QString path, int height, int length)
: QPixmap{ QPixmap{ path }.scaled(size, size) }
{
}