我在图标中使用 SVG 图像QToolButton
s。但我需要能够更改工具按钮的大小,并且需要放大或缩小图标。我的 SVG 图标的原始大小为 24(像素)。麻烦的是QIcon
是它们不会放大到超过原始大小。 (请参阅我的代码中的 attempts0...)
所以我尝试了另一种方法,我覆盖了resizeEvent
并使用QToolButton.setIconSize(event.size())
效果非常好,它允许无限制地放大和缩小。 (参见我的代码中的尝试1...)
但我的问题来了。我确实需要对渲染的图标进行一些像素级的颜色转换。因此我需要得到QImage
我可以从中获得QPixmap
. 但问题是我无法将 SVG 图像渲染为大于 SVG 原始大小的像素图。像素图本身更大,但图像仍然很小,与像素图的中心对齐。我尝试了三种不同的方法,但没有一个有效。 (请参阅我的代码中的尝试2...到尝试4...)
我的代码在这里。为了简单起见,我省略了我对获得的像素图/图像所做的颜色像素变换。
工具栏.h
#pragma once
#include <QToolButton>
class ToolButton : public QToolButton
{
Q_OBJECT
public:
explicit ToolButton(QWidget *parent = nullptr);
protected:
void resizeEvent(QResizeEvent *event) override;
private:
void attempt0_thisDoesNotScaleUp();
void attempt1_thisScalesWellButIdoNotHavePixmap(int w, int h);
void attempt2_thisDoesNotScaleUp(int w, int h);
void attempt3_thisDoesNotScaleUp(int w, int h);
void attempt4_thisDoesNotScaleUp(int w, int h);
QString m_iconName;
};
工具栏.cpp
#include "toolbutton.h"
#include <QDebug>
#include <QPainter>
#include <QResizeEvent>
#include <QtSvg/QSvgRenderer>
ToolButton::ToolButton(QWidget *parent) :
QToolButton(parent)
{
m_iconName = "icon.svg";
// attempt0_thisDoesNotScaleUp(); // uncomment to try attempt 0
}
void ToolButton::resizeEvent(QResizeEvent *event)
{
int w = event->size().width();
int h = event->size().height();
//attempt1_thisScalesWellButIdoNotHavePixmap(name, w, h); // uncomment to try attempt 1
//attempt2_thisDoesNotScaleUp(name, w, h); // uncomment to try attempt 2
//attempt3_thisDoesNotScaleUp(name, w, h); // uncomment to try attempt 3
//attempt4_thisDoesNotScaleUp(name, w, h); // uncomment to try attempt 4
QToolButton::resizeEvent(event);
}
void ToolButton::attempt0_thisDoesNotScaleUp()
{
setIcon(QIcon(m_iconName));
}
void ToolButton::attempt1_thisScalesWellButIdoNotHavePixmap(int w, int h)
{
setIcon(QIcon(m_iconName));
setIconSize(QSize(w, h));
}
void ToolButton::attempt2_thisDoesNotScaleUp(int w, int h)
{
QIcon source(m_iconName);
QPixmap pixmap = source.pixmap(w, h);
QIcon icon;
icon.addPixmap(pixmap);
setIcon(icon);
}
void ToolButton::attempt3_thisDoesNotScaleUp(int w, int h)
{
QSvgRenderer renderer(m_iconName);
QPixmap pm(w, h);
QPainter painter(&pm);
renderer.render(&painter, pm.rect());
QIcon icon;
icon.addPixmap(pm);
setIcon(icon);
}
void ToolButton::attempt4_thisDoesNotScaleUp(int w, int h)
{
QIcon source(m_iconName);
QPixmap pm(w, h);
QPainter painter(&pm);
source.paint(&painter, pm.rect());
QIcon icon;
icon.addPixmap(pm);
setIcon(icon);
}
main.cpp(将工具按钮显示为主窗口,以便能够测试调整大小)
#include "toolbutton.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ToolButton w;
w.show();
return a.exec();
}
为了进行测试,我使用 www.iconmonstr.com 中的 SVG 图标,其原始大小为 24x24 像素。当然,我需要能够将它们缩放到这个大小之上。
我想我错过了一些明显的东西......因为QToolButton::setIconSize(someBiggerSize);
能够放大 SVG 图标。