Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: creating an "svg image button"

Tags:

c++

qt

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() );
}
like image 956
user99974 Avatar asked May 02 '09 20:05

user99974


2 Answers

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 );
}
like image 71
user99974 Avatar answered Sep 23 '22 10:09

user99974


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.

like image 33
shoosh Avatar answered Sep 20 '22 10:09

shoosh