Qt - QIcon in a QTableWidget cell

I have tried many ways to display QIcon in a QTableWidget cell, and I'm not sure why it does not work. I have a button that, when clicked, adds a row to the table. Here is the code ...

void MainWindow::pressed() { QTableWidgetItem *item = new QTableWidgetItem("Hello, world!"); QTableWidgetItem *icon_item = new QTableWidgetItem; QIcon icon("/verified/path/to/icon.png"); icon_item->setIcon(icon); int row = ui->tableFeed->rowCount(); ui->tableFeed->insertRow(row); ui->tableFeed->setItem(row, 0, icon_item); ui->tableFeed->setItem(row, 1, item); } 

And it just doesn't work. Nothing is displayed in this cell. Any ideas?

EDIT: calling setItem, where I set it to icon , was a typo. The actual code sets it to QTabeWidgetItem icon_item . I adjusted it in the code above.

+4
source share
4 answers

You have to set the icon in QTableWidgetItem , and then load the icon element, not the icon itself.

 QTableWidgetItem *item = new QTableWidgetItem("Hello, world!"); QTableWidgetItem *icon_item = new QTableWidgetItem; QIcon icon("/verified/path/to/icon.png"); // It is better to load the icon from the // resource file and not from a path icon_item->setIcon(icon); int row = ui->tableFeed->rowCount(); ui->tableFeed->insertRow(row); ui->tableFeed->setItem(row, 0, icon_item); ui->tableFeed->setItem(row, 1, item); 

If you can see the string element, not the icon, then something is wrong in the icon path.

+2
source

As webclectic pointed out, you probably want to set the icon_item element:

 ui->tableFeed->setItem(row, 0, icon_item); 

... if it really compiled in this way, then I assume that it built an implicit QTableWidgetItem using one of the available constructors .

I'm not sure what will happen if the icon cannot be created from the specified png, but you can also check if the icon is loaded correctly and can be displayed correctly. For example, what icon.isNull() return? What happens if you put it in a shortcut?

Another option is to load the icon from the raster map, so you can make sure that it is really loaded properly:

 QPixmap p; if (!p.load(yourFilename) || p.isNull()) { qDebug() << "Error!"; } QIcon icon = QIcon(p); // and if wanted: label->setPixmap(p) 
+2
source

When I want to add an icon to a cell, I usually do this in a model.

In the data method, you can put them under the role of decoration.

 else if( role == Qt::DecorationRole ) { switch( index.column() ) { case MOVIE: { if( valueAt( index ).toString() == "Godfather" ) return QIcon( ":/16x16/godfather.png" ); } } } 

Hope this helps.

+1
source

You need to first create a resource with prefix icons for their work:

 item = QtGui.QTableWidgetItem() icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/FSTable.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(icon2) 

Sorry the PyQt code above, but you can see that the icon should be set using addPixmap

0
source

Source: https://habr.com/ru/post/1380443/


All Articles