Last active
September 21, 2023 11:23
-
-
Save icecoobe/4a822215da3c2074c1d84d5eaa4ec4be to your computer and use it in GitHub Desktop.
Make some row/col can only accept hex-style input for QTableWidget ;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QLineEdit> | |
#include <QStyledItemDelegate> | |
/* | |
// Sample | |
auto delegate = new HexItemDelegate; | |
ui->tableInfo->setItemDelegateForColumn(1, delegate); | |
ui->tableInfo->setItemDelegateForRow(1, delegate); | |
ui->tableInfo->setItemDelegate(delegate); | |
*/ | |
class HexItemDelegate : public QStyledItemDelegate | |
{ | |
public: | |
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override | |
{ | |
QLineEdit* editor = new QLineEdit(parent); | |
QRegExpValidator* validator = new QRegExpValidator( | |
QRegExp("[0-9A-Fa-f]+$"), editor); | |
editor->setValidator(validator); | |
return editor; | |
} | |
QString displayText(const QVariant& value, const QLocale& locale) const override | |
{ | |
QString text = value.toString(); | |
text.remove('-'); | |
if (text.length() % 2 != 0) | |
{ | |
text.prepend("0"); | |
} | |
// Insert "-" separators every two characters | |
int insertPos = 2; | |
while (insertPos < text.length()) | |
{ | |
text.insert(insertPos, '-'); | |
insertPos += 3; | |
} | |
return text.toUpper(); | |
} | |
void setEditorData(QWidget* editor, const QModelIndex& index) const override | |
{ | |
QLineEdit* lineEdit = qobject_cast<QLineEdit*>(editor); | |
if (lineEdit) | |
{ | |
//QString text = lineEdit->displayText(); // now it's empty | |
//QString text = lineEdit->text(); // now it's empty | |
QString text = index.model()->data(index, Qt::EditRole).toString(); | |
lineEdit->setText(text); | |
} | |
else | |
{ | |
QStyledItemDelegate::setEditorData(editor, index); | |
} | |
} | |
void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override | |
{ | |
QLineEdit* lineEdit = qobject_cast<QLineEdit*>(editor); | |
if (lineEdit) | |
{ | |
QString text = lineEdit->text(); | |
text.remove('-'); | |
model->setData(index, text, Qt::EditRole); | |
} | |
else | |
{ | |
QStyledItemDelegate::setModelData(editor, model, index); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment