我正在编写一个 Qt GUI C++ 程序,我计划在其中填充表格 View ,例如 3X2 表格 View 。该字段中的文本来自 .csv 文件。除了文本之外,还会有一个小图标/图像。
为了了解 UI,它可能看起来有点像;
现在将文本添加到我已经使用过的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/