#include "myexample.h" #include #include #include MyInputDialog::MyInputDialog(QWidget *parent) : QDialog(parent) { m_pEdit = new QLineEdit; QDialogButtonBox *pBtnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); QVBoxLayout *pLayout = new QVBoxLayout(); pLayout->addWidget(m_pEdit); pLayout->addWidget(pBtnBox); setLayout(pLayout); connect(pBtnBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept())); connect(pBtnBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(reject())); } MyInputDialog::~MyInputDialog() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// MyItemDelegate::MyItemDelegate(QWidget *parent) : QStyledItemDelegate(parent) { } MyItemDelegate::~MyItemDelegate() { } QWidget* MyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { // initialize data here instead of using setEditorData Q_UNUSED(option); MyInputDialog *pEditor = new MyInputDialog(parent); QString sValue = index.model()->data(index, Qt::EditRole).toString(); pEditor->setText(sValue); return pEditor; } void MyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { // don't update editor when model changes Q_UNUSED(editor); Q_UNUSED(index); } void MyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (MyInputDialog *pInputDialog = dynamic_cast(editor)) { // here we have the problem that regardless if 'Ok' or 'Cancel' was clicked, the result is Rejected, // so the value will never be set if (pInputDialog->result() == QDialog::Accepted) { QString sValue = pInputDialog->text(); model->setData(index, sValue, Qt::EditRole); } } } void MyItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); editor->move(editor->parentWidget()->mapToGlobal(option.rect.topLeft())); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// MyExample::MyExample(QWidget *parent) : QListWidget(parent) { addItem("Item1"); addItem("Item2"); addItem("Item3"); // set items editable for (int i = 0; i < count(); i++) { item(i)->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled); } setItemDelegate(new MyItemDelegate(this)); } MyExample::~MyExample() { }