【问题标题】:QAbstractTableModel::header data and QML TableViewQAbstractTableModel::header 数据和 QML TableView
【发布时间】:2019-06-04 13:30:50
【问题描述】:

我有 QAbstractTableModel 的子类并提供了 headerData 覆盖:

/**
 * @brief   Obtains the header (columns) names.
 * @param   section: column number.
 * @param   orientation: Accepts only horizontal.
 * @param   role: Accepts only display.
 * @return  The column header text in case all params are valid.
 *          Otherwise empty QVariant.
 */
QVariant CVarTableModel::headerData(int section,
                                    Qt::Orientation orientation,
                                    int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation != Qt::Horizontal)
        return QVariant();

    if (section >= static_cast<int>(Columns::ZCOUNT))
        return QVariant();

    return QVariant::fromValue(static_cast<Columns>(section));
}

我想弄清楚如何让我的 QML TableView 组件利用这个功能。有没有办法自动执行此操作?

【问题讨论】:

    标签: c++ qt qml


    【解决方案1】:

    使用宏 Q_INVOKABLE 从 QML 调用您的方法。然后,在您的 QML 中使用它作为任何其他方法:

    class Model: public QStandardItemModel
    {
    public:
        Model(QObject* parent=nullptr): QStandardItemModel(parent)
        {
            setColumnCount(2);
            setRowCount(2);
        }
    
        Q_INVOKABLE virtual QVariant headerData(int section,
                                            Qt::Orientation orientation,
                                            int role=Qt::DisplayRole) const override
        {
            qDebug() << section << orientation << role;
            if (role != Qt::DisplayRole)
                return QVariant();
    
            if (section == 0)
                return "First Column";
            return "Not first column";
        }
    };
    
    // In main.cpp
    Model* model = new Model();
    
    QQuickView *view = new QQuickView;
    
    view->rootContext()->setContextProperty("myModel", model);
    
    view->setSource(QUrl("qrc:/main.qml"));
    view->show();
    
    TableView {
        TableViewColumn {
            role: "title"
            title: myModel.headerData(0, Qt.Vertical);
            width: 100
        }
        TableViewColumn {
            role: "author"
            title: myModel.headerData(1, Qt.Vertical);
            width: 200
        }
        model: myModel
    }
    

    【讨论】:

    • 感谢您的回答。我现在就是这样做的。我想知道是否有办法让TableView 自己伸手去拿。
    【解决方案2】:

    我今天发现了一个我不知道的不同解决方案:https://doc.qt.io/qt-6/qml-qtquick-controls2-horizontalheaderview.html

    Column{
        HorizontalHeaderView{
            syncView: tableView
        }
        TableView {
            id: tableView
            model: myModel
        }
    }
    

    HorizontalHeaderView 将使用您在模型中提供的headerData

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      相关资源
      最近更新 更多