QT 不使用代理Qtableview怎么设置某个单元格不能选择
时间: 2024-03-10 14:43:36 浏览: 127
如果不想使用代理(QStyledItemDelegate)来实现禁止选择某个单元格的功能,可以通过设置 QTableView 的 itemSelectionChanged 信号来过滤不允许选择的单元格。
具体步骤如下:
1. 继承 QTableView 类,重写 itemSelectionChanged 信号的槽函数:
```c++
class MyTableView : public QTableView
{
Q_OBJECT
public:
MyTableView(QWidget* parent = nullptr)
: QTableView(parent)
{
}
protected:
void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) override
{
// 遍历所有已选择的单元格
for (QModelIndex index : selected.indexes())
{
// 判断单元格是否允许被选择
if (!isCellSelectable(index.row(), index.column()))
{
// 如果单元格不允许被选择,则取消选择该单元格
QItemSelection selection(index, index);
selectionModel()->select(selection, QItemSelectionModel::Deselect);
}
}
// 调用父类的 selectionChanged 函数
QTableView::selectionChanged(selected, deselected);
}
private:
bool isCellSelectable(int row, int column) const
{
// 在这里判断某个单元格是否允许被选择
// 如果允许被选择,返回 true;否则返回 false
return !(row == 1 && column == 1); // 这里以第 2 行第 2 列的单元格为例,不允许被选择
}
};
```
2. 在需要使用 QTableView 的地方,创建一个实例化的 MyTableView 对象:
```c++
// 创建 MyTableView 对象
MyTableView* tableView = new MyTableView(this);
```
这样,就可以实现禁止选择某个单元格的功能了。在上面的例子中,第 2 行第 2 列的单元格将无法被选择。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)