Search code examples
c++qtqt4qtableview

Showing images along with text in QTableView model field


I am writing a Qt GUI C++ program where I am planning to populate a tabular view, for example a 3X2 table view. Where the texts in the field will be from a .csv file. And along with the text there will also be a small icon/image.

To give an idea of the UI it might be looking somewhat like;

enter image description here

Now adding text to QTable model view I have done using;

QStandardItemModel *model = new QStandardItemModel;

QFile file("/home/aj/beta_test.csv");
if (file.open(QIODevice::ReadOnly))
{
    int lineindex = 0;          // file line counter
    QTextStream in(&file);      // read to text stream

    while (!in.atEnd()) {

        QStringList lineToken;
        QString fileLine = in.readLine();   // read one line (separated by "\n")

        lineToken = fileLine.split(",", QString::SkipEmptyParts); // parse a line into separate pieces with "," as the delimiter

        for (int j = 0; j < lineToken.size(); j++)    // load parsed data to model accordingly
        {
            QString value = lineToken.at(j);
            QStandardItem *item = new QStandardItem(value);
            model->setItem(lineindex, j, item);
            ui->tableView->setModel(model);
        }
        lineindex++;
    }
    file.close();
}

Now how to perform adding the image part???


Solution

  • You can use standard method:

    item->setIcon(QIcon("path"));
    

    or do this with index (use setData() and Qt::DecorationRole)

    After adding you can call resizeRowsToContents() to show full images in your cells.

    Also I noticed that you set your model in every iteration. It is not wrong but it is very inefficient (especially when you populate large data), so set your model one time after the loop.