QT的tableview获取当前行
时间: 2023-07-01 20:23:58 浏览: 163
您可以使用QTableView的selectionModel()方法获取选中模型,然后使用selectedRows()方法获取选中的行。以下是一个示例代码:
```cpp
QItemSelectionModel *select = ui->tableView->selectionModel();
QModelIndexList selectedRows = select->selectedRows();
if(!selectedRows.empty()){
int currentRow = selectedRows.at(0).row();
// currentRow即为当前选中行的行号
}
```
请注意,此代码假定只选择了一行。如果选择了多行,则需要对选中的行进行迭代。
相关问题
qttableview获取当前选中行
要获取当前选中行的索引,可以使用QTableView的selectionModel()方法来获取选择模型,然后使用selectedIndexes()方法获取所选单元格的索引列表,最后使用row()方法获取第一个所选索引的行数。例如:
```
QModelIndexList indexes = ui->tableView->selectionModel()->selectedIndexes();
int rowIndex = indexes.at(0).row();
```
这将获取所选单元格的第一个索引的行号。如果你只想获取所选行的行号,而不是所选单元格的索引,请使用selectedRows()方法来获取所选行的索引列表,然后使用first()方法获取第一个所选行的索引。例如:
```
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
int rowIndex = indexes.first().row();
```
请注意,如果没有选中任何行,则selectedIndexes()和selectedRows()方法都将返回一个空列表,因此在使用它们之前应该先进行检查。
qt tableview添加一行
添加一行到 Qt TableView 中有多种方法,以下是其中一种常用的方法:
1. 在 TableView 中,使用 model()->rowCount() 方法获取当前表格中已有的行数。
2. 使用 model()->insertRow(row) 方法在表格中插入新的一行。其中,row 参数为插入的位置,即在第 row 行之前插入新的一行,如果不指定位置则会在表格的末尾添加一行。
3. 使用 model()->setData(index, value) 方法为新行中的单元格设置值。其中,index 参数为新行中单元格的索引,value 参数为要设置的值。
下面是示例代码:
```
// 获取当前表格中已有的行数
int row = model()->rowCount();
// 插入新的一行
model()->insertRow(row);
// 设置新行中单元格的值
model()->setData(model()->index(row, 0), "value1");
model()->setData(model()->index(row, 1), "value2");
model()->setData(model()->index(row, 2), "value3");
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)