Qt - Cannot put an image in a table

2019-01-25 21:44发布

Why with the following code I just get an empty table widget?

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);

How can I put an image into a QTableWidgetItem?

Thank you.

P.S.:
I noticed that the table is not really empty. Clicking on the different QTableWidgetItem elements, the empty ones become blue, the one with coordinates [0,0] is highlighted differently: cyan with a thin blue bar on the left...

2条回答
狗以群分
2楼-- · 2019-01-25 22:14

OK, I had to rescale the image:

thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img).scaled(100, 100));
查看更多
仙女界的扛把子
3楼-- · 2019-01-25 22:20

You are doing all almost right, but try to control your img, for example, like this:

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!";
}

Hope, it helps you! Good luck!

查看更多
登录 后发表回答