qtableview 只能输入数字
时间: 2023-11-14 22:00:54 浏览: 63
QTableView 是一个用于显示表格数据的 Qt 组件,它本身并不限制用户输入的内容类型。如果你想限制用户只能输入数字,可以通过 QItemDelegate 类来实现。
具体来说,你可以在自定义的 QItemDelegate 类中重写 createEditor() 方法,创建一个 QLineEdit 编辑器,并设置它的输入限制为数字。例如,以下代码片段演示了如何限制输入整数:
```
class NumberDelegate : public QItemDelegate {
public:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
QLineEdit *editor = new QLineEdit(parent);
QIntValidator *validator = new QIntValidator(editor);
editor->setValidator(validator);
return editor;
}
};
```
然后,在 QTableView 中设置这个自定义的 QItemDelegate 类即可:
```
NumberDelegate *delegate = new NumberDelegate;
tableView->setItemDelegate(delegate);
```
这样,用户就只能在 QTableView 中输入数字了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)