Qt的 - 不能把图像中的表(Qt - Cannot put an image in a table

2019-07-18 07:32发布

为什么用下面的代码我只是得到一个空表窗口小部件?

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?

谢谢。

PS:
我注意到,该表是不是真的空。 点击不同的QTableWidgetItem元素时,空的变成蓝色,在一个坐标[0,0]中的高亮方法不同:青与左边薄蓝条...

Answer 1:

你正在做的一切差不多吧,但要尽量控制自己的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!";
}

希望,它可以帮助你! 祝好运!



Answer 2:

OK,我不得不重新调整图像:

thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img).scaled(100, 100));


文章来源: Qt - Cannot put an image in a table