QWidget *CustomDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QLineEdit *editor = new QLineEdit(parent);
QRegExpValidator *validator = new QRegExpValidator(QRegExp("[\\x4e00-\\x9fa5]+"), editor); // 中文字符范围
editor->setValidator(validator);
editor->setStyleSheet("");
connect(editor, &QLineEdit::textChanged, this, [=](const QString &text){
QFontMetrics metrics(editor->font());
int width = metrics.width(text) + 10;
editor->setFixedWidth(qMax(width, 100));
});
return editor;
}
void CustomDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QLineEdit *lineEdit = static_cast<QLineEdit *>(editor);
lineEdit->setText(value);
}
void CustomDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QLineEdit *lineEdit = static_cast<QLineEdit *>(editor);
QString value = lineEdit->text();
model->setData(index, value, Qt::EditRole);
}
int y = QRandomGenerator::global()->generate();//随机数
int w = QRandomGenerator::global()->bounded(10000);//范围内随机数