Qt: creating an "svg image button"


Question

I'm new to Qt so please excuse my ignorance.

I am attempting to create a an 'svg image button' with QSizePolicy::Preferred for both horizontal and vertical. That part works. When the window is resized, the button grows and shrinks exactly how I want... But the image within the button stays the same size. I would like the image to scale with the button. I tried to overload resizeEvent, and call setImageSize, but that infinitely recurses.

#ifndef SVGPUSHBUTTON_H
#define SVGPUSHBUTTON_H

#include <QtGui>

class SVGPushButton : public QPushButton
{
public:
    SVGPushButton(QString path, QString name = "");
    ~SVGPushButton();

    void resizeEvent(QResizeEvent * event);
private:
};

#endif // SVGPUSHBUTTON_H

#include "SVGPushButton.h"

SVGPushButton::SVGPushButton(QString svgPath, QString name)
: QPushButton(name)
{
    QIcon icon(svgPath);
    setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
    setFlat(true);
    setIcon(icon);
}

SVGPushButton::~SVGPushButton()
{}

void SVGPushButton::resizeEvent(QResizeEvent * event)
{
    setIconSize( event->size() );
}
1
7
1/4/2011 2:20:38 PM

Accepted Answer

This is how I eventually solved it:

SVGPushButton::SVGPushButton(QString svgPath, QString name)
: QPushButton()
{
    setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
    QSvgWidget *icon = new QSvgWidget(svgPath,this);
    setLayout( new QHBoxLayout(this) );
    layout()->addWidget( icon );
}
5
5/3/2009 1:41:24 AM

From looking over the docs, it looks like what you want to do is have a QLabel in the button. Then call setPixmap() on the label, and then set the property scaledContents() to true.

Now I'm not sure if just adding a label to the button will work, because the button has an icon and text property already.

I'll mark this as a community wiki so you can change it if you want.

Also, from my experience, messing with resizeEvent() is rarely a good idea :-)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon