qtmvc实现,model总共8列数据,代理其中第7列为icon
时间: 2024-03-20 08:39:34 浏览: 107
如果你想在QtMVC中使用代理来显示第7列的图标数据,可以按照以下步骤实现:
1. 创建一个继承自QStyledItemDelegate的代理类,例如:
```
class IconDelegate : public QStyledItemDelegate
{
public:
IconDelegate(QObject *parent = nullptr);
// ...
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
};
```
2. 在代理类中实现paint()函数,使用QPainter绘制图标,并将其居中绘制在单元格中,例如:
```
void IconDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.column() == 6) {
QIcon icon = index.model()->data(index, Qt::DecorationRole).value<QIcon>();
if (!icon.isNull()) {
QRect rect = option.rect;
rect.setWidth(rect.height());
rect.adjust(2, 2, -2, -2);
icon.paint(painter, rect, Qt::AlignCenter);
}
} else {
QStyledItemDelegate::paint(painter, option, index);
}
}
```
3. 在View中,使用setItemDelegateForColumn()函数为第7列设置代理,例如:
```
MyModel *model = new MyModel(this);
QTableView *tableView = new QTableView(this);
tableView->setModel(model);
tableView->setItemDelegateForColumn(6, new IconDelegate(this));
```
4. 如果需要编辑第7列的图标数据,还需要在代理类中实现createEditor()和setEditorData()函数,以及commitData()函数,例如:
```
QWidget *IconDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.column() == 6) {
QFileDialog *dialog = new QFileDialog(parent);
dialog->setFileMode(QFileDialog::ExistingFile);
dialog->setNameFilter(tr("Images (*.png *.xpm *.jpg)"));
connect(dialog, &QFileDialog::fileSelected, [this](const QString &path) {
emit commitData(dialog);
emit closeEditor(dialog);
});
return dialog;
} else {
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
void IconDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (index.column() == 6) {
QString path = index.model()->data(index, Qt::DecorationRole).toString();
QFileDialog *dialog = qobject_cast<QFileDialog *>(editor);
dialog->selectFile(path);
} else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
void IconDelegate::commitData(QWidget *editor)
{
QFileDialog *dialog = qobject_cast<QFileDialog *>(editor);
QModelIndex index = qobject_cast<QAbstractItemDelegate *>(sender())->index();
QString path = dialog->selectedFiles().value(0);
QIcon icon(path);
index.model()->setData(index, icon, Qt::DecorationRole);
}
```
希望这些步骤可以帮助你在QtMVC中使用代理来展示和编辑第7列的图标数据。
阅读全文