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() );
}
Was it helpful?

Solution

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

OTHER TIPS

Avoiding the infinite recursion is easy. Add a boolean data member to your SVGPushButton that indicates you're inside a resize event and check it when you enter the event like so:

void SVGPushButton::resizeEvent (QResizeEvent * event)
{
    if (m_insideResize)
        return;
    m_insideResize = true;
    // call setImageSize()...
    m_insideResize = false;
}

With this you'll be able to make sure that this actually does what you want it to do. After you get it to work you can try to find out what causes the the recursive call. My guess is that you set the size of the image to be slightly bigger than it should be and this causes the button to want to resize again etc'.
The proper way to solve it then is to figure out the right size you want to resize the image to.
After this works, I would still leave the recursion check in place just in case, to be safe.

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 StackOverflow
scroll top