如何在每一行中显示图标使用QSqlRelationalTableModel和QTableView

时间:2013-03-21 06:59:13

标签: qt qtableview

现在,我尝试使用QSqlRelationalTableModel和QTableView在数据库中显示我的数据,根据正确的“fileType”,例如“doc,txt,exe,sln”来显示第一列中的图标。

    dirModel=new QSqlRelationalTableModel(this);
    dirModel->setTable("ecm_doc");
    dirModel->setFilter(QString("creatoruserid='%1' and parentid='%2'").arg(userid).arg(parentid));
    dirModel->select();
    dirView=new QTableView(this);
    dirView->setItemDelegate(new DirDelegate(this));

    dirView->setModel(dirModel);
    dirView->setSelectionMode(QAbstractItemView::SingleSelection);

     showIcon();

void DirTree::showIcon()
{
    int rowCount = dirModel->rowCount();
    for(int row = 0; row < rowCount; row++)
    {
//here is a test.
        QModelIndex index = dirModel->index(row, 1);
        QIcon folderIcon(style()->standardPixmap(QStyle::SP_DirClosedIcon));
        dirModel->setData(index, folderIcon, Qt::DecorationRole);
    }
}

帮帮我,在线等待:)

1 个答案:

答案 0 :(得分:0)

您应该从QSqlRelationalTableModel继承并重新实现data()函数以指定图标:

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    // I assume that 1 is the db table column with the filetype property 
    if (index.column() == 1 && role == Qt::DecorationRole)
    {
       QSqlRecord r = modelRecord(index.row());
       QString fileType = r.field(1).value().toString();

       QIcon icon; 
       if (fileType == "exe")
          icon = QIcon(":/PathToIcon/exe.png");
       else if (fileType == "sln")
          icon = QIcon(":/PathToIcon/sln.png"); 
       ...
       return QVariant(icon);
    }

    return QSqlRelationalTableModel::data(index, role);
}