6
我有一個QTableView
,我想驗證用戶輸入。 如果用戶在QTableView
的單元格中插入了無效值,我想突出顯示該單元格並禁用QPushButton
。在QTableView驗證用戶輸入
我該如何做到這一點?我可以使用QValidator
嗎?
我有一個QTableView
,我想驗證用戶輸入。 如果用戶在QTableView
的單元格中插入了無效值,我想突出顯示該單元格並禁用QPushButton
。在QTableView驗證用戶輸入
我該如何做到這一點?我可以使用QValidator
嗎?
是的,你可以做到這一點,爲此使用自定義QItemDelegate
(我用QIntValidator
作爲例子)。
頁眉:
#ifndef ITEMDELEGATE_H
#define ITEMDELEGATE_H
#include <QItemDelegate>
class ItemDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit ItemDelegate(QObject *parent = 0);
protected:
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget * editor, const QModelIndex & index) const;
void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const;
void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const;
signals:
public slots:
};
#endif // ITEMDELEGATE_H
.cpp的
#include "itemdelegate.h"
#include <QLineEdit>
#include <QIntValidator>
ItemDelegate::ItemDelegate(QObject *parent) :
QItemDelegate(parent)
{
}
QWidget *ItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QLineEdit *editor = new QLineEdit(parent);
editor->setValidator(new QIntValidator);
return editor;
}
void ItemDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QString value =index.model()->data(index, Qt::EditRole).toString();
QLineEdit *line = static_cast<QLineEdit*>(editor);
line->setText(value);
}
void ItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *line = static_cast<QLineEdit*>(editor);
QString value = line->text();
model->setData(index, value);
}
void ItemDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
用法:
#include "itemdelegate.h"
//...
ItemDelegate *itDelegate = new ItemDelegate;
ui->tableView->setItemDelegate(itDelegate);
在這種情況下,用戶將無法輸入錯誤的數據,但可以使用未來:
void ItemDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *line = static_cast<QLineEdit*>(editor);
QIntValidator validator;
int pos = 0;
QString data = line->text();
if(validator.validate(data,pos) != QValidator::Acceptable)
{
qDebug() << "not valid";//do something
}
else
{
model->setData(index, data);
}
}
但在這種情況下,請不要忘記從您的代碼中刪除editor->setValidator(new QIntValidator);
行
謝謝,它的工作原理。但是當我插入一個有效的輸入時,我不能刪除單元格中的數字。我該怎麼辦? – splunk 2014-10-28 19:57:18
@Aimcorz我想你使用我的第一個例子,所以在我的計算機驗證器塊輸入,但改變選擇到另一個單元正常工作。我可以建議你使用我的第二個例子,提供一些方法來避免這種情況,例如設置空字符串'model-> setData(index,「」,Qt :: EditRole);'或其他。 – Chernobyl 2014-10-28 20:05:06