QT-QTablewidget 设置选中某一行

要在 QTableWidget 中设置选中的行,可以使用 setCurrentItem() 函数来设置当前的 QTableWidgetItem。你可以通过调用 QTableWidget 的 item() 函数获得指定行和列的 QTableWidgetItem,然后通过将其传递给 setCurrentItem() 函数来设置选中的行。

下面是一个示例代码,演示了如何设置 QTableWidget 中的选中行:

#include 
#include 
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 创建一个 QTableWidget 对象
    QTableWidget tableWidget;
    
    // 设置表格的行数和列数
    tableWidget.setRowCount(3);
    tableWidget.setColumnCount(2);
    
    // 在指定行和列中添加 QTableWidgetItem
    QTableWidgetItem* item1 = new QTableWidgetItem("Row 1");
    tableWidget.setItem(0, 0, item1);
    
    QTableWidgetItem* item2 = new QTableWidgetItem("Row 2");
    tableWidget.setItem(1, 0, item2);
    
    QTableWidgetItem* item3 = new QTableWidgetItem("Row 3");
    tableWidget.setItem(2, 0, item3);
    
    // 设置选中行
    int rowToSelect = 1; // 要选中的行的索引
    QTableWidgetItem* selectedItem = tableWidget.item(rowToSelect, 0);
    tableWidget.setCurrentItem(selectedItem);
    
    // 显示 QTableWidget
    tableWidget.show();

    return a.exec();
}

在示例代码中,我们首先创建了一个 QTableWidget 对象 tableWidget,并设置了行数和列数。然后,我们使用 setItem() 函数向指定行和列添加 QTableWidgetItem。

接下来,我们将要选中的行的索引存储在 rowToSelect 变量中,并使用 item() 函数获取相应的 QTableWidgetItem。最后,我们将选中的 QTableWidgetItem 设置为当前项,通过调用 setCurrentItem() 函数来设置选中的行。

请注意,行索引从 0 开始计数,即第一行的索引为 0。

这样,你就可以在 QTableWidget 中设置选中的行了。选中的行将被高亮显示。

你可能感兴趣的:(qt)