0

现在,我尝试使用 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);
    }
}

帮帮我,在线等待:)

4

1 回答 1

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);
}
于 2013-03-21T11:44:53.227 回答