how to add Custom Widget to QListView in C++ qt
To add a custom widget to a QListView in C++ Qt, you need to create a delegate class that inherits from QStyledItemDelegate. This delegate class will handle the painting and interaction with the custom widget.
Here are the steps to add a custom widget to a QListView:
- Create a custom widget class that inherits from QWidget. This widget should contain the controls and layout that you want to display in the list view.
Example:
class MyCustomWidget : public QWidget {
public:
MyCustomWidget(QWidget *parent = nullptr) : QWidget(parent) {
// create controls and layout here
QLabel *label = new QLabel("My Custom Widget");
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(label);
setLayout(layout);
}
};
- Create a delegate class that inherits from QStyledItemDelegate. This class will handle the painting and interaction with the custom widget.
Example:
class MyDelegate : public QStyledItemDelegate {
public:
MyDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
Q_UNUSED(option)
Q_UNUSED(index)
MyCustomWidget *widget = new MyCustomWidget(parent);
return widget;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const override {
Q_UNUSED(editor)
Q_UNUSED(index)
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override {
Q_UNUSED(editor)
Q_UNUSED(model)
Q_UNUSED(index)
}
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
Q_UNUSED(index)
editor->setGeometry(option.rect);
}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
Q_UNUSED(option)
if (index.isValid()) {
MyCustomWidget *widget = qobject_cast<MyCustomWidget *>(editor(index));
if (widget) {
painter->save();
painter->translate(option.rect.topLeft());
widget->render(painter);
painter->restore();
}
}
}
};
- Set the delegate for the QListView using the setItemDelegate() method.
Example:
QListView *listView = new QListView();
MyDelegate *delegate = new MyDelegate(listView);
listView->setItemDelegate(delegate);
Now, when you add items to the list view, the delegate will create a MyCustomWidget for each item and display it in the list view. You can customize the appearance and behavior of the widget by modifying the MyDelegate class.
原文地址: https://www.cveoy.top/t/topic/Atu 著作权归作者所有。请勿转载和采集!