Skip to content

Instantly share code, notes, and snippets.

@icecoobe
Last active September 21, 2023 11:23
Show Gist options
  • Save icecoobe/4a822215da3c2074c1d84d5eaa4ec4be to your computer and use it in GitHub Desktop.
Save icecoobe/4a822215da3c2074c1d84d5eaa4ec4be to your computer and use it in GitHub Desktop.
Make some row/col can only accept hex-style input for QTableWidget ;
#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