0
votes

I'm learning how to use Qt for C++ programming. I have this image I want to display after when I click at a button and the position on a matrix related to that button is equal to -1, I also want to clear the text on that same button, my code up to now for that part is:

if(Tabuleiro[x][y] == -1){
    this->Botoes[x][y]->setText("");
    this->Botoes[x][y]->setIcon(QIcon("bomba.png"));
}

Being that Tabuleiro is a matrix of int, Botoes is a matrix of pointers to QPushButtons and "bomba.png" is the image I want to display. The image is in the same folder as the project, but once I run it is not displayed. I also tryed using Qt Resource system, I created a new resource called imagens.qrc on it I created a prefix /Imagem and placed my image there, this is what the code looked like after this:

if(Tabuleiro[x][y] == -1){
        this->Botoes[x][y]->setText("");
        this->Botoes[x][y]->setIcon(QIcon(":/Imagem/bomba.png"));
    }

But it still won't work. What am I doing wrong? Also, I tryed using

this->Botoes[x][y]->text().clear();

instead of

this->Botoes[x][y]->setText("");

But it didn't work, do you know why?

1
Make sure the PNG in the working directory of your application (where executable is). - Archie
@Archie working directory is not the same thing as executable directory - Kamil Klimek
@joão-areias consider using Qt resource system doc.qt.io/qt-5/resources.html - Kamil Klimek
Thanks Archie, it wasn't but that still didn't solve it - João Areias
Thanks @KamilKlimek I just tried using Qt resource but still didn't work :( - João Areias

1 Answers

3
votes

Please include <QApplication> and <QStyle> and try:

this->Botoes[x][y]->setIcon( qApp->style()->standardIcon( QStyle::SP_MessageBoxWarning ) );

If it works (warning icon being displayed): then, it means you're not loading your resources correctly.

You can also check this:

QPixmap foo( ":/Imagem/bomba.png" );
bool found = !foo.isNull(); // true if png file was found, false if it was not

If false, again, it means you're not loading your resources correctly, if true, icon should be displayed in the button.

Morevover, you can also try this->Botoes[x][y]->setIconSize( QSize(16,16) ) because if someone earlier did this->Botoes[x][y]->setIconSize( QSize(0,0) ); your button icon will not be displayed!