QFileSystemModel是Qt框架中用于展示文件系统的模型类,它提供了文件和目录的数据以及图标。要在使用QFileSystemModel时显示图标,你需要使用QStyledItemDelegate来自定义项的外观。
首先,创建一个继承自QStyledItemDelegate的自定义代理类。然后,在其paint()方法中获取文件的图标,并在合适的位置进行绘制。可以使用QIcon::pixmap()方法将图标转换为QPixmap对象,并使用QPainter在项上绘制该图像。
以下是一个简单示例:
#include <QtWidgets>
class IconDelegate : public QStyledItemDelegate {
public:
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override {
if (index.column() == 0) {
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
QIcon icon = QFileIconProvider().icon(index.data(QFileSystemModel::FileTypeRole).value<QFileInfo>().isDir() ? QFileInfo("") : index.data(QFileSystemModel::FilePathRole).value<QFileInfo>());
QPixmap pixmap = icon.pixmap(option.rect.height(), option.rect.height());
painter->save();
painter->drawPixmap(option.rect.x(), option.rect.y(), pixmap);
painter->restore();
}
else {
QStyledItemDelegate::paint(painter, option, index);
}
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QTreeView treeView;
QFileSystemModel model;
IconDelegate delegate;
treeView.setItemDelegate(&delegate);
treeView.setModel(&model);
// 设置代理列
treeView.setItemDelegateForColumn(0, &delegate);
model.setRootPath(QDir::rootPath());
treeView.show();
return app.exec();
}
在上面的示例中,我们创建了一个自定义代理类IconDelegate,并重写了paint()方法。在paint()方法中,我们根据文件类型获取相应的图标,并将其绘制到项的指定位置。
注意,在使用QFileSystemModel时,我们还设置了代理列来确保只有第一列显示图标。可以根据需要自行调整和扩展该示例代码以满足特定需求。
内容由零声教学AI助手提供,问题来源于学员提问