如何在Qt for QTableView中使用自定义QProxy合并列?

时间:2017-11-19 14:34:45

标签: qt pyqt

我使用RxPy与某些QSqlTableModel相关联。

我必须在QTableView的同一列中显示firstNamesecondName。 我还必须分别按这些字段进行搜索,这是一个问题:我不能在我的SQL查询中使用QTableView,我必须保留CONCAT(lastName, ' ', secondName)和{{1分别在某些数据结构中

firstName

现在,例如,我想按secondName

对表格进行排序

1 个答案:

答案 0 :(得分:1)

在表格模型中创建自己的数据结构

typedef struct sUserFullName
{
   QString oFistName;
   QString oLastName;
}USER_FULLNAME;
Q_DECLARE_METATYPE(USER_FULLNAME);

class MyCusumeModel : public QSqlTableModel
{
     Q_OBJECT

private:

    QList<USER_FULLNAME> m_oAllUsersNames;

    const QString& GetFirstName(int row) const
    {
       return m_oAllUsersNames.at(row).oFistName;
    }
    const QString& GetLastName(int row) const
    {
       return m_oAllUsersNames.at(row).oLastName;
    }

  public:

    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;

};

处理cpp中的列数据:

QVariant MyCusumeModel::data(const QModelIndex &index, int role) const
{
   // Valid index ?
   if (!index.isValid())
       return QVariant();

   // Validate size overflow.
   if (index.row() >= m_oAllUsersNames.size()) {
       return QVariant();
   }

   // Handle column data 
   switch (index.column()) {

   case 0: // Combine first + last Name
     if (role == Qt::DisplayRole)
       return QString("%1, %2").arg(GetFirstName(index.row())).arg(GetLastName(index.row()));
     if (role == Qt::UserRole) 
       return m_oAllUsersNames(index.row()); // store data
     break;

  default:
     break;
 }
 return QVariant();

}

用于排序lessThan

中的覆盖QSortFilterProxyModel

按姓氏排序的示例:

bool MyCustomeSortModel::lessThan(const QModelIndex &oLeft, const QModelIndex &oRight) const
{
    USER_FULLNAME sLeftData = sourceModel()->data(oLeft, Qt::UserRole).value<USER_FULLNAME>();
    USER_FULLNAME sRightData = sourceModel()->data(oRight,Qt::UserRole).value<USER_FULLNAME>();   

    switch (oLeft.column()) {

    case 0:  // Sort by last name
        return sLeftData.oLastName < sRightData.oLastName;
        break;

    default:
        break;
    }

    // Sort any other supported type
    return sourceModel()->data(oLeft, Qt::DisplayRole) < sourceModel()->data(oRight, Qt::DisplayRole);
}