QT Quick QML 实例之定制 TableView


所有的热爱都要不遗余力,真正喜欢它便给它更高的优先级,和更多的时间吧!

GIT工程源码在这里:     QmlLearningPro编译选择 TableView

QML其它文章请点击这里:     QT QUICK QML 学习笔记


一、演示

● 效果如下:
请添加图片描述

二、C++关键步骤

在Qt中,如使用 QML 的 TableView 并且想要将数据与C++类进行绑定,通常会继承 QAbstractTableModel 来实现自定义的数据模型

1. beginInsertRows()(用户插入行)

beginInsertRows 是 Qt 中的 QAbstractItemModel 类的一部分,用于通知视图 (view) 即将向模型 (model) 中插入行。这个方法通常与 endInsertRows 配对使用,以确保模型的内部数据和视图保持一致。

void MyModel::insertRows(int position, int rows, const QModelIndex &parent = QModelIndex()) {
    // 通知视图即将插入行
    beginInsertRows(parent, position, position + rows - 1);

    // 执行实际的数据插入操作
    // 例如:
    for (int row = 0; row < rows; ++row) {
        dataList.insert(position, newRowData);
    }

    // 通知视图插入行操作已经完成
    endInsertRows();
}

2. roleNames() (表格中列映射)

roleNames() 是 QAbstractItemModel 类中的一个虚函数,通常用于返回模型中的角色(roles)与角色名称(role names)之间的映射。角色在 Qt 的模型-视图框架中用于区分不同类型的数据(例如显示数据、编辑数据、工具提示等)。

//为每个角色提供一个名称,主要用于 QML 绑定。
QHash<int, QByteArray> TargetCoordinate::roleNames() const
{
    QHash<int, QByteArray> roles;

    roles.insert(lngRole,  "lng");
    roles.insert(latRole,  "lat");
    roles.insert(altRole,  "alt");

    return roles;
}

QML 中使用:

	TableViewColumn {
	    role: "lng"   //来源于C++中roleNames
	    title: "Longitude"
	    resizable: true
	}

	TableViewColumn {
	    role: "lat"   
	    title: "Latitude"
	    resizable: true
	}
	
	TableViewColumn {
	    role: "alt"  
	    title: "Altitude"
	    resizable: true
	}

3. data() (用户获取数据)

在 Qt 的 QAbstractItemModel 类中,data() 函数用于返回模型中某个特定项的数据信息。这个函数通常和 roleNames() 函数结合使用,以便为不同的角色返回相应的数据。

视图(如ListView)中请求模型的数据时,视图会调用 data() 函数,并传递相应的 QModelIndex 和 role, data() 函数会根据这些参数返回对应的数据。

QVariant TargetCoordinate::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() < 0 || index.row() >= m_coordinates.count())
        return QVariant();
    const QGeoCoordinate &coordinate = m_coordinates.at(index.row());
    
    switch(role)
    {
        case lngRole:
            return QString::number(coordinate.longitude(), 'f', 6);
        case latRole:
            return QString::number(coordinate.latitude(), 'f', 6);
        case altRole:
            return QString::number(coordinate.altitude(), 'f', 2);
    }
    return QVariant();
}

data() 和 roleNames()关系:

data():提供模型项在特定角色下的数据。
roleNames():为每个角色提供一个名称,主要用于 QML 绑定。

4. headerData() (表头)

headerData() 是 QAbstractItemModel 类中的另一个重要虚函数,用于提供模型的表头信息。在 Qt 的模型-视图框架中,表头用于显示列标题或行标题,通常用于 QTableView、QTreeView 或类似的视图中。

QVariant TargetCoordinate::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();
    /* 当请求的方向为 Qt::Horizontal 时,我们返回与请求的 section(列索引)相关的表头数据。*/
    if (orientation == Qt::Horizontal) {
        if (section == 0)
            return tr("lng");
        else if (section == 1)
            return tr("lat");
        else if (section == 2)
            return tr("alt");
    }
    return QVariant();
}

headerData() 通常与 data() 一起使用,前者用于表头的显示,后者用于表格中具体单元格的显示。

5. flags (某个单元格的特性标志)

flags 用于返回模型中某个项的特性标志(flags)。这些标志指示该项是否可选中、可编辑、可拖放等行为。通过重写 flags() 函数,可以控制模型中每个项的交互行为。

Qt::ItemFlags TargetCoordinate::flags(const QModelIndex &index) const
{
    qDebug() << "flags()" ;

    if (!index.isValid())
        return Qt::NoItemFlags;

    return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}

常见的 Qt::ItemFlag 枚举值:

Qt::NoItemFlags: 表示没有特性,项不可交互。
Qt::ItemIsSelectable: 该项是可选择的。
Qt::ItemIsEditable: 该项是可编辑的。
Qt::ItemIsDragEnabled: 该项支持拖动操作。
Qt::ItemIsDropEnabled: 该项支持放置操作。
Qt::ItemIsUserCheckable: 该项可以显示一个复选框,允许用户进行选择。
Qt::ItemIsEnabled: 该项是可用的(如果未设置,则该项将显示为禁用状态)。

6. setData (用户更新数据)

功能:

编辑数据: 当用户在视图中编辑数据(如在表格单元格中输入文本或选择复选框)时,视图会调用 setData() 函数,模型根据提供的新数据更新相应的项。

拖放操作: 如果支持拖放操作,当数据被放置到模型中的某个位置时,setData() 可能会被调用以插入新数据。

批量数据更新: 你可以在外部批量修改模型的数据,每次修改后调用 setData() 更新特定的项

bool TargetCoordinate::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || role != Qt::EditRole)
        return false;

    if (index.row() < 0 || index.row() >= m_coordinates.count())
        return false;

    QGeoCoordinate &coordinate = m_coordinates[index.row()];
    if (index.column() == 0)
        coordinate.setLongitude(value.toDouble());
    else if (index.column() == 1)
        coordinate.setLatitude(value.toDouble());
    else if (index.column() == 2)
        coordinate.setAltitude(value.toDouble());

    //表示仅有一个单元格的数据发生了更改
    emit dataChanged(index, index);
    return true;
}

组合使用
setData() 与 data():setData() 用于更新数据,而 data() 则用于获取数据。视图在显示数据时调用 data(),在用户修改数据时调用 setData()。

flags():在 flags() 函数中设置 Qt::ItemIsEditable 标志,以确保该项可编辑。只有当项是可编辑的,视图才会调用 setData()。

dataChanged 信号:在 setData() 中调用 emit dataChanged(index, index),通知视图相应项的数据已经改变。视图会自动重新绘制受影响的项。

三、QML UI 显示

TableView {
    id: tableView
    anchors.margins:    10
    anchors.fill:       parent
    model:       coordinateModel
    //表格属性
    itemDelegate: {
        return editableDelegate;
    }
    rowDelegate: Rectangle {
        color : styleData.selected ? "#7db9f7" : (styleData.alternate ? "#f5f1f1":"#a89d9d")
        height: 30
    }

    TableViewColumn {
        role: "lng"   //来源于C++中roleNames
        title: "Longitude"
        resizable: true
    }

    TableViewColumn {
        role: "lat"   //y
        title: "Latitude"
//                width: 120
        resizable: true
    }

    TableViewColumn {
        role: "alt"   //
        title: "Altitude"
        resizable: true
    }

    headerDelegate: Rectangle {
        implicitWidth: heardText.width
        implicitHeight: heardText.height * 1.6
        gradient:       styleData.pressed ? pressG : (styleData.containsMouse ? hoverG: normalG)
        border.width: 1
        border.color: "gray"
        Text {
            id:     heardText
            anchors.centerIn: parent
            font.pixelSize: 22
            text:           styleData.value
            color:          styleData.pressed ? "red" : "blue"
            font.bold: true
        }
    }
    
    Component {
        id: editableDelegate
        Rectangle {
            border.color: "gray"
            border.width: 1
            Item{
                anchors.centerIn: parent
                height:  showTXT.height * 1.2
                width:   showTXT.width * 1.2

                Text {
                    id:showTXT
                    anchors.centerIn: parent
                    elide: styleData.elideMode
                    text: styleData.value !== undefined ? styleData.value : ""
                    color: styleData.selected ? "red" : "black"//styleData.textColor
                    font.pixelSize:  18
                    horizontalAlignment: Text.AlignHCenter
                }
            }
        }
    }

    RowLayout {
        anchors.horizontalCenter:   rootRect.horizontalCenter
        anchors.top:                rootRect.bottom
        anchors.topMargin:          20
        Button {
            text:  "add"
            onClicked:      {
     			coordinateModel.insertRowsCoor(tableView.currentRow+1, 1);

                tableView.currentRow = tableView.currentRow + 1
                tableView.refreshTableView
            }
        }
        Button {
            text:  "delete"
            onClicked:      {
                if(tableView.rowCount ===0)  return

                if(tableView.currentRow === -1)    coordinateModel.removeRowsCoor(tableView.currentRow-1);
                else    coordinateModel.removeRowsCoor(tableView.currentRow);

                tableView.refreshTableView
            }
        }
    }

具体代码见工程源码


GIT 工程文件点击这里:     QmlLearningPro编译选择 TableView

QML 其它文章请点击这里:     QT QUICK QML 学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值