【问题标题】:How to add text to a cell of a tablewidget如何将文本添加到表格小部件的单元格
【发布时间】:2015-09-10 15:51:50
【问题描述】:

我的应用程序中有一个表格小部件。它有 2 列,包括文件名和文件路径。我想用一个按钮向这个 tablewidget 添加文本,并使用这个文本来做一些操作。这该怎么做?

【问题讨论】:

  • 我需要一些我认为的功能,但我不知道我应该使用哪些功能?
  • 你有没有试过用谷歌搜索?像“qtablewidget 添加行”?你读过一些结果吗?
  • 是的,但我有一个问题。我需要向单元格添加文本,而不是项目。在谷歌的结果中,它显示了带有项目的方法。
  • 是的,您不能直接将文本添加到 QTableWidget 单元格,您必须通过 QTableWidgetItem 来完成(一次一个单元格)
  • 我从目录中获取文件名并将它们添加到 tablewidget。那么,如何使用 QTableWidgetItem 来做到这一点?

标签: c++ qt qt-designer qt5.3


【解决方案1】:

您不能将文本 (QString) 直接添加到 QTableWidget,您必须先创建一个 QTableWidgetItem,然后将其插入到所需的单元格中。示例:

// create a new qtablewidget
QTableWidget tablewidget;

// our tablewidget has 2 columns
tablewidget.setColumnCount(2);

// we insert a row at position 0 because the tablewidget is still empty
tablewidget.insertRow(0);

// we add the items to the row we added
tablewidget.setItem(0, 0, new QTableWidgetItem("first row, first column"));
tablewidget.setItem(0, 1, new QTableWidgetItem("first row, second column"));

如果你有更多的列,方法是一样的

如果您想添加更多行(即使使用第一行也很好),您可以使用泛型

tablewidget.insertRow(tablewidget.rowCount());

它总是在表的末尾添加一个新行(追加);

更难:这应该解释insertRow() 与不存在的appendRow() 有何不同(和强大)

QTableWidget tablewidget;
tablewidget.setColumnCount(2);

// we insert a row at position 0 because the tablewidget is still empty
tablewidget.insertRow(tablewidget.rowCount());

tablewidget.setItem(0, 0, new QTableWidgetItem("first row, first column"));
tablewidget.setItem(0, 1, new QTableWidgetItem("first row, second column"));

// "append" new row at the bottom with rowCount()
tablewidget.insertRow(tablewidget.rowCount());
tablewidget.setItem(1, 0, new QTableWidgetItem("second row, first column"));
tablewidget.setItem(1, 1, new QTableWidgetItem("second row, second column"));

// we insert a "new" second row pushing the old row down
tablewidget.insertRow(1);
tablewidget.setItem(1, 0, new QTableWidgetItem("this push the"));
tablewidget.setItem(1, 1, new QTableWidgetItem("second row down"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多