Qt - Cannot put an image in a table

后端 未结 3 730
一生所求
一生所求 2020-12-18 12:47

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

QString imgPath = \"C:\\\\path\\\\to\\\\image.jpg\";
QImage *img = new QImage(imgPath);

QTable         


        
相关标签:
3条回答
  • 2020-12-18 13:26

    You can try the following - here we use images from the resource folder...

    QString imgPath = ":/image.png";
    QImage imageName = *new QImage(imgPath);
    
    QTableWidgetItem *thumbnail = new QTableWidgetItem;
    thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(imageName));
    

    and then - set the thumbnail to the table row/col you want to have - for example in col 1 and row 1:

    tableWidget->setItem( 1, 1, thumbnail);
    

    you have to note that you need the specific header file:

    #include <QPixmap>
    
    0 讨论(0)
  • 2020-12-18 13:32

    OK, I had to rescale the image:

    thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img).scaled(100, 100));
    
    0 讨论(0)
  • 2020-12-18 13:35

    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!

    0 讨论(0)
提交回复
热议问题