QTableView当前索引被删除时,怎么不滑动
时间: 2024-01-21 12:05:12 浏览: 28
可以使用`QTableView::scrollTo()`函数将视图滚动到先前的索引位置。在当前索引被删除后,你可以使用`QTableView::currentIndex()`获取新的当前索引,然后使用`scrollTo()`函数将视图滚动到该位置。下面是一个示例代码:
```cpp
QModelIndex current = tableView->currentIndex();
model->removeRow(current.row());
tableView->scrollTo(current);
```
在这个示例中,`tableView`是一个`QTableView`对象,`model`是该表视图所使用的模型。当当前索引被删除后,首先获取新的当前索引,然后使用`scrollTo()`函数将视图滚动到该位置。这样就可以保持视图不会自动滑动到表格的顶部或底部。
相关问题
QTableView当前索引被删除时,如何才能避免滚动到底部
当QTableView中的当前索引被删除时,如果希望避免滚动到底部,可以通过以下方法实现:
1. 获取当前QTableView的滚动条位置。
2. 删除当前索引。
3. 设置QTableView的滚动条位置。
下面是一个示例代码:
```
QModelIndex currentIndex = ui->tableView->currentIndex(); // 获取当前索引
int scrollBarPosition = ui->tableView->verticalScrollBar()->value(); // 获取滚动条位置
model->removeRow(currentIndex.row()); // 删除当前索引所在的行
ui->tableView->verticalScrollBar()->setValue(scrollBarPosition); // 设置滚动条位置
```
这样做可以保持QTableView的滚动位置不变,并且在删除当前索引后继续保持当前视图状态。
QTableView如何点击后当前的索引不可见
你可以使用QAbstractItemView中的scrollTo()函数来实现这个功能。在单击QTableView中的项目时,使用该函数将当前项目滚动到视图的中心,并将其设置为不可见。
以下是一个示例代码:
```python
from PyQt5.QtWidgets import QTableView, QAbstractItemView
class MyTableView(QTableView):
def __init__(self, parent=None):
super().__init__(parent)
self.setEditTriggers(QAbstractItemView.NoEditTriggers) # 禁止编辑
self.setSelectionBehavior(QAbstractItemView.SelectRows) # 选中整行
self.setSelectionMode(QAbstractItemView.SingleSelection) # 单选模式
def mousePressEvent(self, event):
index = self.indexAt(event.pos())
if index.isValid():
# 将当前索引滚动到视图中心
self.scrollTo(index, QAbstractItemView.PositionAtCenter)
# 将当前索引设置为不可见
self.setRowHidden(index.row(), True)
super().mousePressEvent(event)
```
在上面的代码中,我们定义了一个MyTableView类,它继承自QTableView。我们重写了它的mousePressEvent()方法以处理单击事件。当单击一个项目时,我们首先使用indexAt()函数获取当前索引。如果索引有效,我们使用scrollTo()函数将其滚动到视图的中心,并使用setRowHidden()函数将其设置为不可见。最后,我们调用父类的mousePressEvent()方法以确保其他处理仍然发生。
你可以根据需要调整代码来满足你的需求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)