QTableView如何判断当前的索引是否可见
时间: 2023-08-10 07:03:14 浏览: 49
可以使用QAbstractItemView类中的方法indexVisible(const QModelIndex& index)来判断索引是否可见。该方法返回一个bool类型的值,如果索引可见则返回true,否则返回false。
示例代码:
```c++
// 判断当前选中的索引是否可见
if(ui->tableView->indexWidget(ui->tableView->currentIndex()) &&
ui->tableView->isIndexHidden(ui->tableView->currentIndex()))
{
qDebug() << "当前选中的索引不可见";
}
else
{
qDebug() << "当前选中的索引可见";
}
```
在上面的代码中,我们先判断当前选中的索引是否有widget,如果有则说明该索引不可见。如果没有widget,则再调用isIndexHidden方法判断该索引是否可见。
相关问题
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()方法以确保其他处理仍然发生。
你可以根据需要调整代码来满足你的需求。
QTableView当前索引被删除时,怎么不滑动
可以使用`QTableView::scrollTo()`函数将视图滚动到先前的索引位置。在当前索引被删除后,你可以使用`QTableView::currentIndex()`获取新的当前索引,然后使用`scrollTo()`函数将视图滚动到该位置。下面是一个示例代码:
```cpp
QModelIndex current = tableView->currentIndex();
model->removeRow(current.row());
tableView->scrollTo(current);
```
在这个示例中,`tableView`是一个`QTableView`对象,`model`是该表视图所使用的模型。当当前索引被删除后,首先获取新的当前索引,然后使用`scrollTo()`函数将视图滚动到该位置。这样就可以保持视图不会自动滑动到表格的顶部或底部。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)