c++ - 在 QTableView 模型字段中显示图像和文本

标签 c++ qt qt4 qtableview

我正在编写一个 Qt GUI C++ 程序,我计划在其中填充表格 View ,例如 3X2 表格 View 。该字段中的文本来自 .csv 文件。除了文本之外,还会有一个小图标/图像。

为了了解 UI,它可能看起来有点像;

enter image description here

现在将文本添加到我已经使用过的QTable模型 View 中;

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() 以在单元格中显示完整图像。

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

关于c++ - 在 QTableView 模型字段中显示图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27597133/

相关文章:

c++ - 模板化类中的模板化方法

QT 按钮/停止按钮

c++ - 如何创建紧凑的 Qt4 vBoxLayout

c++ - 如何用空格填充 QString?

c - 使用 QtCreator [mac os] 找不到 -lrt 的库

C++ 在 std::vector 中搜索和计算特定元素的最快方法是什么?

c++ - 在C++单元测试上下文中,抽象基类是否应具有其他抽象基类作为函数参数?

c++ - 在我按下 ENTER 后,程序没有输出任何结果。为什么会这样?

c++ - QString 到 char* 的转换

ios - 无法在 QT 项目中添加 iOS OpenCV 框架