Qt - QTableWidget 单元格中的 QIcon
我尝试了多种方法在 QTableWidget 单元格中显示 QIcon,但我不确定为什么它不起作用。我有一个按钮,按下该按钮会在表格中添加一行。这是代码...
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);
}
但它不起作用。该单元格中没有显示任何内容。有什么想法吗?
编辑:我将其设置为 icon
的 setItem 调用是一个拼写错误。实际代码将其设置为QTabeWidgetItem icon_item
。我已经在上面的代码中更正了它。
I have tried numerous ways to display a QIcon in a QTableWidget cell and I am not sure why it is not working. I have a button that when pressed 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 that cell. Any ideas?
EDIT: the setItem call where I set it to icon
was a typo. The actual code sets it to the QTabeWidgetItem icon_item
. I have corrected it in the code above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当我想向单元格添加图标时,我通常在模型中进行。
在数据方法中,您可以将它们放在装饰角色下。
希望这有帮助。
When I want to add an icon to a cell, I usually do it in the model.
In the data method you can put them under the decoration role.
Hope this helps.
正如 webclectic 所指出的,您可能希望将该项设置为
icon_item
:...如果它确实以这种方式编译,那么我猜它正在使用其 可用构造函数。
我不确定如果无法从指定的 png 构造图标会发生什么,但您也可以检查以确保图标确实已正确加载并且可以正确显示。例如,
icon.isNull()
返回什么?如果将其放入标签中会发生什么?另一种选择是从像素图中加载图标,以便您可以验证它是否确实正确加载:
As webclectic pointed out, you probably want to set the item to
icon_item
:...if it indeed compiled that way then I'd guess it's constructing an implicit QTableWidgetItem using one of its available constructors.
I'm not sure what happens if the icon can't be constructed from the specified png, but you might also check to make sure that the icon was indeed loaded correctly and can be displayed correctly. For example, what does
icon.isNull()
return? What happens if you put it in a label?Another option is to load the icon from a pixmap so you can verify that it is indeed loaded properly:
您必须首先创建一个带有前缀图标的资源才能工作:
请原谅上面是 PyQt 代码,但您可以看到图标必须使用
addPixmap
设置You'll have to first create a resource with prefix icons for these to work:
Pardon that the above is a PyQt code, but you can see the icon must be set up using
addPixmap
您必须将图标设置为
QTableWidgetItem
,然后加载图标项而不是图标本身。如果您可以看到字符串项而不是图标,则图标路径有问题。
You have to set the icon to a
QTableWidgetItem
and then load the icon item and not the icon itself.If you can see the string item and not the icon then something is wrong with the icon path.