为什么使用以下代码我只得到一个空表小部件?
QString imgPath = "C:\\path\\to\\image.jpg";
QImage *img = new QImage(imgPath);
QTableWidget *thumbnailsWidget = new QTableWidget;
QTableWidgetItem *thumbnail = new QTableWidgetItem;
thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img));
thumbnailsWidget->setColumnCount(5);
thumbnailsWidget->setRowCount(3);
thumbnailsWidget->setItem(0, 0, thumbnail);
setCentralWidget(thumbnailsWidget);
如何将图像放入QTableWidgetItem?
谢谢。
P.S .:
我注意到桌子不是空的。单击不同的QTableWidgetItem元素,空的元素变为蓝色,坐标为[0,0]的元素以不同的方式突出显示:青色,左侧有一个细蓝色条...
答案 0 :(得分:7)
你做的一切几乎都是正确的,但试着控制你的img
,例如,像这样:
QString imgPath = "C:\\path\\to\\image.jpg";
QImage *img = new QImage();
bool loaded = img->load(imgPath);
if (loaded)
{
QTableWidget *thumbnailsWidget = new QTableWidget;
QTableWidgetItem *thumbnail = new QTableWidgetItem;
thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img));
thumbnailsWidget->setColumnCount(5);
thumbnailsWidget->setRowCount(3);
thumbnailsWidget->setItem(0, 0, thumbnail);
w.setCentralWidget(thumbnailsWidget);
} else {
qDebug()<<"Image "<<imgPath<<" was not opened!";
}
希望,它可以帮到你!祝你好运!
答案 1 :(得分:3)
好的,我不得不重新缩放图像:
thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img).scaled(100, 100));
答案 2 :(得分:2)
您可以尝试以下操作-在这里我们使用资源文件夹中的图像...
QString imgPath = ":/image.png";
QImage imageName = *new QImage(imgPath);
QTableWidgetItem *thumbnail = new QTableWidgetItem;
thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(imageName));
然后-将缩略图设置为您想要的表行/列-例如第1行和第1行:
tableWidget->setItem( 1, 1, thumbnail);
您必须注意,您需要特定的头文件:
#include <QPixmap>