微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 在QSqlTableModel的QTableView列中显示图像

我很好奇如何在QTableView中显示数据库中的图像.

是否有类似QTableWidgetItem的东西,我可以在QTableView中使用它?

我使用QsqlTableModel.

解决方法

一个粗略的想法是使用 QStandardItem::setData在其上设置Qpixmap(转换为QVariant),然后您可以在 QStandardItemModel上设置QStandardItem.

顺序:QImage —> Qpixmap —> QVariant —> QStandardItem —> QStandardItemmodel

例如:

QStandardItemmodel *model = new QStandardItemmodel;
QImage image(":/cat/lovers/own/myCat.jpg");
QStandardItem *item = new QStandardItem();
item->setData(QVariant(Qpixmap::fromImage(image)),Qt::decorationRole);
model->setItem(0,item);
ui->tableView->setModel(model);

您必须调整图像大小或单元格大小,具体取决于您的需要.

[编辑]

如果您使用的是QsqlTableModel,请继续使用它.我们需要做的就是将这些路径字符串放入Qpixmap,并将该项角色设置为该列中的Qt :: decorationRole.

正如文件所说:

Each item has a number of data elements associated with it and they can be retrieved by specifying a role (see Qt::ItemDaTarole) to the
model’s data() function.

要做到这一点,概念很简单:提供QTableView和QVariant的QVariant,因为QTableView根据Qt::DecorationRole渲染它们.

您可以继承QsqlTableModel并重新实现虚函数QVariant data(const QModelIndex & index,int role = Qt::DisplayRole)并使图像列返回Qpixmap作为QVariant,具有装饰角色.所以做这样的事情:

QVariant CustomsqlTableModel::data(const QModelIndex &idx,int role = Qt::displayRole) const
{
     if (idx.column() == imageColumn) {
         QString imgFile = QsqlTableModel::data(idx,Qt::displayRole); // get path string

        if (role == Qt::displayRole) 
            return QString(); // return the path string for display role

        QImage image(imgFile);
        /* some modification to the image,maybe */

        Qpixmap pixmap(imgFile);
        if (role == Qt::decorationRole)
            return pixmap;   // return Qpixmap for decoration role

        if (role == Qt::SizeHintRole)
            return pixmap.size(); // in case need the image size

     }
     return QsqlTableModel::data( idx,role ); // use original data() outside the imageColumn
}

此外,您还可以尝试子类化qstyledItemDelegate并重新实现paint()函数自定义您自己的委托,但这需要更复杂的工作.使用委托的示例可以在here找到.您可以使用委托,even a button绘制任何您想要的内容.

*对不起代码没有经过测试,因为我手头没有数据库.

原文地址:https://www.jb51.cc/c/115938.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐