Skip to content

Instantly share code, notes, and snippets.

@mitchcurtis
Created October 19, 2021 12:14
Show Gist options
  • Save mitchcurtis/28f4b9ecef6bf4f2444a1fc55e72d6d3 to your computer and use it in GitHub Desktop.
Save mitchcurtis/28f4b9ecef6bf4f2444a1fc55e72d6d3 to your computer and use it in GitHub Desktop.
A hacky way of setting a custom delegate for QListView
#include <QtWidgets>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow mainWindow;
QWidget *centralWidget = new QWidget;
mainWindow.setCentralWidget(centralWidget);
QVBoxLayout *vBoxLayout = new QVBoxLayout(centralWidget);
auto listView = new QListView(centralWidget);
QStandardItemModel model(100, 1);
for (int row = 0; row < model.rowCount(); ++row) {
QStandardItem *item = new QStandardItem(QString("row %0").arg(row));
model.setItem(row, 0, item);
}
listView->setModel(&model);
// This makes the widget always visible, whereas the custom delegate
// approach doesn't, and manages memory better as a result.
// To do it properly, subclass QStyledItemDelegate and reimplement createEditor():
// https://doc.qt.io/qt-5/qtwidgets-itemviews-stardelegate-example.html
for (int row = 0; row < 10; ++row) {
auto slider = new QSlider;
slider->setOrientation(Qt::Horizontal);
listView->setIndexWidget(model.index(row, 0), slider);
}
vBoxLayout->addWidget(listView);
mainWindow.centralWidget()->setLayout(vBoxLayout);
mainWindow.resize(400, 400);
mainWindow.show();
return app.exec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment