QTableView点击某行后会滚动
时间: 2023-07-04 14:09:51 浏览: 129
这可能是由于QTableView的默认行为导致的。当用户单击某行时,QTableView会尝试将该行滚动到视图的中心位置,以便用户可以更好地查看该行的内容。
如果您不希望发生这种行为,您可以尝试通过以下方法禁用它:
```python
tableView.verticalScrollMode(QAbstractItemView.ScrollPerPixel)
```
这将使QTableView在滚动时以像素为单位进行滚动,而不是滚动到行的中心位置。
相关问题
QTableView点击后滚动
默认情况下,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 选项将单元格滚动到视图的中心位置,但您也可以选择其他位置。
QT QTableView怎么保持一行不滚动
要保持 QTableView 中的一行不滚动,可以通过设置 QTableView 的垂直滚动条的范围来实现。具体方法如下:
1. 获取要保持不滚动的行号,假设为 rowIndex。
2. 获取 QTableView 的垂直滚动条,可以通过 QTableView 的 verticalScrollBar() 函数获取。
3. 设置垂直滚动条的范围,使得 rowIndex 行的上方和下方都能够滚动,而 rowIndex 行本身不能滚动。具体实现如下:
```cpp
QScrollBar* vScrollBar = tableView->verticalScrollBar(); // 获取垂直滚动条
int rowHeight = tableView->rowHeight(rowIndex); // 获取行高
int rowTop = tableView->rowViewportPosition(rowIndex); // 获取行顶部位置
int rowBottom = rowTop + rowHeight; // 获取行底部位置
int scrollRangeTop = vScrollBar->minimum(); // 获取滚动条范围的最小值
int scrollRangeBottom = vScrollBar->maximum() - vScrollBar->pageStep(); // 获取滚动条范围的最大值
vScrollBar->setRange(scrollRangeTop, scrollRangeBottom); // 设置滚动条范围
vScrollBar->setValue(qMax(rowTop - rowHeight, scrollRangeTop)); // 将滚动条滚动到 rowIndex 行的上方
vScrollBar->setPageStep(rowHeight); // 设置滚动条的页大小为行高
```
这样,就可以保持 QTableView 中的一行不滚动了。