PDA

View Full Version : Default delegate displays empty QLineEdit?



andy.fillebrown
14th April 2009, 18:09
It is strange to me that the default delegate for QListView displays an empty QLineEdit widget during editing instead of one filled with the text from the model's DisplayRole data. It makes me think I am doing something wrong, or inefficiently. Here is my current solution...



/*
[1] Reimplement "setEditorData" in a subclass of QStyledItemDelegate so that it puts
the text in the editor (selected by default, as expected) instead of leaving it blank.
*/

void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QStyledItemDelegate::setEditorData(editor, index);

if (editor->inherits("QLineEdit"))
{
QLineEdit *e = static_cast<QLineEdit*>(editor);
e->setText(index.data(Qt::DisplayRole).toString());
}
}

/*
[2] Set MyDelegate as the item delegate for the view before "show()"...
*/

void MyMainWindow::showListView()
{
[...]

MyListModel *model = new MyListModel(this);
model->setScene(this->currentScene());

MyDelegate *delegate = new MyDelegate(this);

QListView *view = new QListView;
view->setModel(model);
view->setItemDelegate(delegate); // <---[2]
view->show();

[...]
}


...is it really necessary to subclass QStyledItemDelegate to get the desired result, or am I missing something?

Cheers,
-andy.f

spirit
14th April 2009, 18:28
does index.data(Qt::DisplayRole).toString() return something?
what you will see in console if you execute this code?


...
qDebug() << index.data(Qt::DisplayRole).toString();
qDebug() << index.data(Qt::EditRole).toString();
...

wysota
15th April 2009, 00:51
The delegate's edit functionality works on EditRole thus you have to return data from this role for your custom models and you have to accept data for this role in setData() if you want the default delegate to be able to edit your model.

andy.fillebrown
16th April 2009, 14:13
Ok, problem solved... from your replies it seemed likely the problem was in my code so I looked things over more carefully and found a bug in my QAbstractListModel::data reimplementation...

was:


[...]

if (role != Qt::DisplayRole || role != Qt::EditRole)
return QVariant();

// return data...

[...]


fixed:


[...]

if (role != Qt::DisplayRole && role != Qt::EditRole)
return QVariant();

// return data...

[...]


Thanks,
-andy.f