QTableView点击后滚动
时间: 2023-07-05 19:09:12 浏览: 176
默认情况下,QTableView 在被单击后不会自动滚动。如果您希望在单击单元格时自动滚动,请按照以下步骤操作:
1. 创建一个子类化 QTableView 的新类。
2. 重写 mousePressEvent() 方法,并在其中获取单元格的位置信息。
3. 使用 scrollTo() 方法将视图滚动到单元格的位置。
以下是一个示例:
```python
from PyQt5.QtWidgets import QTableView, QApplication
from PyQt5.QtCore import QModelIndex, Qt
class MyTableView(QTableView):
def __init__(self, parent=None):
super(MyTableView, self).__init__(parent)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
index = self.indexAt(event.pos())
if index.isValid():
self.scrollTo(index, QTableView.PositionAtCenter)
super(MyTableView, self).mousePressEvent(event)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
table_view = MyTableView()
# ... 设置表格模型和数据 ...
table_view.show()
sys.exit(app.exec_())
```
在上面的示例中,我们创建了一个新类 MyTableView,它子类化了 QTableView。我们重写了 mousePressEvent() 方法,并在其中获取单元格的位置信息。然后,我们使用 scrollTo() 方法将视图滚动到单元格的位置。最后,我们调用父类的 mousePressEvent() 方法以确保其他事件处理程序能够正常工作。
请注意,scrollTo() 方法接受两个参数:要滚动到的索引和位置。在上面的示例中,我们使用 QTableView.PositionAtCenter 选项将单元格滚动到视图的中心位置,但您也可以选择其他位置。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)