非常抱歉,我在之前的代码中有一个错误。由于自定义的CustomWidget类没有名为setText()的成员函数,所以应该使用setFont()来设置标签的文本。以下是修正后的代码:
#include <QApplication>
#include <QListView>
#include <QWidget>
#include <QVBoxLayout>
class CustomWidget : public QWidget {
public:
explicit CustomWidget(const QString& text, QWidget* parent = nullptr) : QWidget(parent) {
QVBoxLayout* layout = new QVBoxLayout(this);
QLabel* label = new QLabel(text, this);
layout->addWidget(label);
}
};
class WidgetDelegate : public QStyledItemDelegate {
public:
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override {
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
// 绘制背景和边框
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
painter->fillRect(opt.rect, opt.state & QStyle::State_Selected ? QColor("#E8F2FE") : QColor(Qt::white));
painter->drawRoundedRect(opt.rect.adjusted(1, 1, -1, -1), 5, 5);
painter->restore();
// 绘制文本
QRect textRect = opt.rect.adjusted(10, 0, -10, 0);
painter->save();
painter->setPen(opt.palette.color(QPalette::Text));
painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter,
opt.fontMetrics.elidedText(index.data().toString(), Qt::ElideRight, textRect.width()));
painter->restore();
}
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override {
return QSize(100, 30); // 自定义元素的大小
}
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override {
Q_UNUSED(option);
CustomWidget* editor = new CustomWidget(index.data().toString(), parent);
return editor;
}
void setEditorData(QWidget* editor, const QModelIndex& index) const override {
if (CustomWidget* customWidget = qobject_cast<CustomWidget*>(editor)) {
QLabel* label = customWidget->findChild<QLabel*>(); // 获取子部件中的标签
if (label) {
label->setFont(index.data(Qt::FontRole).value<QFont>()); // 设置字体
}
}
}
void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override {
if (CustomWidget* customWidget = qobject_cast<CustomWidget*>(editor)) {
QLabel* label = customWidget->findChild<QLabel*>(); // 获取子部件中的标签
if (label) {
QFont font = label->font();
model->setData(index, font, Qt::FontRole); // 将字体设置为数据模型中的值
}
}
}
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
QStringList data;
data << "Item 1" << "Item 2" << "Item 3";
QListView listView;
// 使用自定义委托
WidgetDelegate delegate;
listView.setItemDelegate(&delegate);
// 创建一个模型并设置数据
QStandardItemModel model;
for (const QString& item : data) {
QStandardItem* itemObj = new QStandardItem(item);
model.appendRow(itemObj);
}
listView.setModel(&model);
listView.show();
return app.exec();
}
对于编辑器部分,我们通过customWidget->findChild<QLabel*>()找到CustomWidget中的QLabel,并使用setFont()函数来设置字体。
非常抱歉给您带来困扰,希望这次的修复能解决问题。如果您有任何其他疑问,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问




