TableView标头

时间:2019-07-15 11:32:08

标签: c++ qt qtableview qheaderview

我到处都在浏览,但是找不到关于如何在Qt Creator中为 TableView 创建某种类型的标题的任何信息。

我希望它看起来像这样:

TableView

1 个答案:

答案 0 :(得分:2)

简短答案:QTCreator中没有可用于定义表视图标题的设置...

长答案:那就是带有自定义模型的TableView。 然后您需要定义一个继承QAbstractTableModel的新模型

然后在FooModel标头中覆盖headerData方法

class FooModel : public QAbstractTableModel
{
    Q_OBJECT

    //...
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
    //... more methods may be here

然后在cpp中输入

QVariant FooModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole)
    {
        switch (section)
        {
        case 0:
            return QString("Name");
        case 1:
            return QString("ID");
        case 2:
            return QString("HexID");
        // etc etc    
        }

    }
    return QVariant();
}

最后进入控制器:

    myFooModel  = new FooModel(this);
    ui->myTableView->setModel(myFooModel);