开发者

Different headers for two table which inherit from the same tableModel class

I have 2 tableViews that inherit from the same class (TableModel) which in turn inherits from QAbstractTableModel. I would like to add headers for the 2 tables but these headers should be different for each table. In my TableModel I have this method:


    QVariant TableModel::headerData(int section, Qt::Orientation ori开发者_如何转开发entation, int role) const
    {
        if (role != Qt::DisplayRole)
            return QVariant();

        if (orientation == Qt::Horizontal) {
            switch (section) {
            case 0:
                return tr("Header1");

            case 1:
                return tr("Header2");

            case 2:
                return tr("Header3");

            default:
                return QVariant();
            }
        }
        return QVariant();
    }

But that will only work for one of the tables. How could I set different headers for the other table?


One simple way would be to make a proxy model for one or the other table view, and override the header information via the proxy model. For this application, it shouldn't be very difficult.

That said, I wonder about the circumstances that lead to columns somehow meaning something different for the same data, merely in a different table.


Another simple way would be to create a property in your model that allowed you to set the value of the headers. For example:

public class TableModel {
    Q_PROPERTY(QString header1 header1 setHeader1);
    QString _header1;
    // ...
public:
    QString header1() { return _header1; }
    void setHeader1(const QString& header) { _header1 = header; }
    // ...
};

And then you can return header1() in you data function:

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Horizontal) {
        switch (section) {
        case 0:
            return header1();

        case 1:
            return header2();

        case 2:
            return header3();

        default:
            return QVariant();
        }
    }
    return QVariant();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜