在QTableView模型字段中显示图像和文本 我正在编写一个QTQGUI C++程序,我计划填充一个表格视图,例如一个3x2表视图。其中字段中的文本将来自.csv文件。除了文本,还有一个小图标/图像

在QTableView模型字段中显示图像和文本 我正在编写一个QTQGUI C++程序,我计划填充一个表格视图,例如一个3x2表视图。其中字段中的文本将来自.csv文件。除了文本,还有一个小图标/图像,c++,qt,qt4,qtableview,C++,Qt,Qt4,Qtableview,要想了解UI,它可能看起来有点像 现在将文本添加到我使用的QTable模型视图中 QStandardItemModel *model = new QStandardItemModel; QFile file("/home/aj/beta_test.csv"); if (file.open(QIODevice::ReadOnly)) { int lineindex = 0; // file line counter QTextStream in(&fil

要想了解UI,它可能看起来有点像

现在将文本添加到我使用的QTable模型视图中

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

现在如何执行添加图像部分

您可以使用标准方法:

item->setIcon(QIcon("path"));
或者使用索引使用setData和Qt::DecorationRole来实现这一点

添加后,可以调用resizeRowsToContents在单元格中显示完整图像


我还注意到,您在每次迭代中都设置了模型。这并没有错,但效率非常低,尤其是在填充大数据时,所以在循环之后再设置一次模型。

那么我的答案呢?有帮助吗?我没有得到任何反馈。很抱歉,我在家遇到了一些问题,所以耽搁了一点时间,我一定会尽快通知你的。非常感谢。