Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a QWidget in a Qt View
    text
    copied!<p>Problem: I have a simple QStringListModel that I want to display in a view. However, I want each item in the view to be a custom QWidget that I have created. I do not understand why this is such a difficult problem! I have scoured the internet for solutions and, although I find bits and pieces here and there, no good solution fits all my needs.</p> <p>The basic code for setting up my model/view:</p> <pre> <code> QStringList strings; // add some strings to the model QStringListModel* model = new QStringListModel(strings); QListView* view = new QListView; view->setModel(model); </code> </pre> <p>I have tried various attempts at doing this to no avail.</p> <p><b>Attempt #1</b></p> <p>I tried subclassing a new QItemDelegate object. Inside this object, I overrode the methods for creating an editor. I followed all the steps for setting up that delegate. The problem is that when the view is populated with the model, it grabs each item in the model in Qt::DisplayRole when I need it to grab each item in Qt::EditRole.</p> <p><b>Attempt #2</b></p> <p>Another method I tried was to subclass a QListView, and override the setModel method to call setIndexWidget for each item in the model. My code looks something this:</p> <pre> <code> void CustomListView::setModel(QAbstractItemModel* model) { QListView::setModel(model); for (int i = 0; i rowCount(); ++i) { QModelIndex index = model->index(i, 0); CustomWidget* widget = new CustomWidget; setIndexWidget(index, widget); } } </code> </pre> <p>This worked as far as adding my CustomWidget object to each row in the list view. In order to ensure that the regular model data was not also shown beneath my CustomWidget objects, I also overrode CustomListView::paintEvent(QPaintEvent* event) to do nothing. Again, this worked. </p> <p>But my major issue now is that when the list is displayed, although my CustomWidgets are displayed on it properly, the background of the list is a solid white color. I tried calling setAutoFillBackground(false) on the CustomListView but that did nothing. I want my list view to have a transparent background.</p> <p>Any feedback on this problem would be <i>greatly</i> appreciated. I have spent a lot of time trying to get this to work! Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload