简体   繁体   中英

qt5 view different roles of model data

I want to use a QTableView to show different roles of an item, eg column 1 shows the DisplayRole data, column 2 shows UserRole, column 3 shows UserRole+1, etc

I've created this by making my own item delegate and assigning it to the appropriate column. However, to get access to the same item the delegates have to access their siblings. For example, here's my setEditorData function:

void UserRoleDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QModelIndex baseIndex = index.sibling(index.row(),0);
    QVariant v = baseIndex.data(Qt::UserRole);
    if(v.isValid())
        static_cast<QLineEdit*>(editor)->setText(v.toString());
}

Right now, it's hardcoded that column 0 contains the real object and other columns just access that via the sibling function. I'm worried, though, that it's fragile in that changing the column order will break it.

There are obvious ways to manage that, but I'm just wondering if I'm taking the right approach. Is there a better option to display different aspects of the same item?

To avoid possible code rewrite you simple could use the enumeration for your column numbers. For example:

enum ColumnNumber {
    Base,
    Sub1,
    Sub2
}

And in your delegate's code:

[..]
QModelIndex baseIndex = index.sibling(index.row(), Base);

Thus, if you need to change the column order, you simply need to change the order of your enum values. The rest of code will work correctly as it is.

WRT to item delgate usage - it looks rather strange. Such things used to made in the model class, especially in QAbstractItemModel::data(...) function, using it with Qt::EditRole role. For example:

QVariant Model::data(const QModelIndex &index, int role) const
{
    if (role == Qt::EditRole) {
        // Get the data that stored in the first column
        // ..
        return data;
    }
    [..]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM