0

I am creating a Qt application and I have an image that I want to use for a button instead of text. Unfortunately all that shows up is an empty button.

I've tried two different methods to get it to show up with the same results for both methods.

Code for Method 1:

ui->setupUi(this);

QPixmap pix(":/svg/resources/menu.svg");
int w = ui->menuButton->width();
int h = ui->menuButton->height();
ui->menuButton->setMask(pix.scaled(w,h,Qt::KeepAspectRatio).mask());

I found the info for the second method here: Adding image to QPushButton on Qt

Code for Method 2:

ui->setupUi(this);

QIcon icon(":/svg/resources/menu.svg");
ui->menuButton->setIcon(icon);

Could someone please help me figure out why my image isn't showing up and the button is just empty?

James
  • 124
  • 10
  • Have you checked that the resource is being loaded correctly -- [pix.isNull()](http://doc.qt.io/qt-5/qpixmap.html#isNull) for the first example, [icon.isNull()](http://doc.qt.io/qt-5/qicon.html#isNull) for the second. Note, also, that in the first example you give you are using the alpha mask from the scaled pixmap to set the shape of the [`QPushButton`](http://doc.qt.io/qt-5/qwidget.html#setMask) -- not setting the pixmap itself. – G.M. Oct 24 '18 at 19:42
  • I checked it, it is a null pixmap... – James Oct 24 '18 at 20:58
  • When I try against the icon instead of the pixmap it doesn't show as null, however. But I'm still getting the same result. – James Oct 24 '18 at 21:05

2 Answers2

0

You use .svg image format. Are you sure your application load image format plugin for .svg? Image plugins must be in directory "imageformats" in current directory of your application. Avaliable plugins you can find in Qt directory .../Desktop/Qt/<version>/<mingw or msvc>/plugins/imageformats

Serhiy Kulish
  • 1,057
  • 1
  • 6
  • 8
  • I checked this directory. I see dlls for svg in there. I went ahead and tried to do it with a jpeg as well and got the same result. – James Oct 24 '18 at 21:03
0

In my project using .svg images as button icons are no problem, maybe the button size is missing, try:

ui->menuButton->setIcon(QIcon(":/svg/resources/menu.svg"));
ui->menuButton->setToolTip("optional tooltip");
ui->menuButton->setFixedSize(QSize(28,28));

Assuming you stored your icons correctly in a resource file. If not, create a new: right click on your top project folder (in the project-tree) -> Add new.. -> choose Qt on the left an Qt Resource File on the right window -> a new Window apears.

Add Prefix -> Add Files (your icon)

Hoehli
  • 154
  • 10
  • Btw, your solution led me to realize that I was creating my variables incorrectly. I had previously done `QIcon icon(":/svg/resources/menu.svg");` instead of `QIcon icon = QIcon(":/svg/resources/menu.svg");`. Upon changing it to the latter piece of code everything worked without me having to specify the size. – James Oct 25 '18 at 14:24