QT6 源(132)二维表模型 QStandardItemModel 的条目类型QStandardItem :本篇的源代码都是条目 QStandardItem 的源代码

(1)首先给出二维表模型的相关类的继承关系,这是分析的基础

在这里插入图片描述

(2)搭建一个最简单的例子,两行三列的二维表,作为随后测试的例子框架

在这里插入图片描述

(3)接着以上面的程序为例子,测试与学习条目类型 QStandardItem 的一些成员函数的使用

在这里插入图片描述

++

在这里插入图片描述

(4)

在这里插入图片描述

++测试如下 ,可见,行列成员函数是与模型索引重复的 :

在这里插入图片描述

++再次区分下这两个函数

在这里插入图片描述

(5)返回本条目的类型,是否是自定义的

在这里插入图片描述

(6)本条目可以与数据流进行读写,还不会用数据流,不举例了 :

在这里插入图片描述

(7)以下的成员函数,说明本条目 QStandardItem 可以容纳子表,进而构成树形结构 model。因为没有学习完毕,就不举例了。但这些成员函数都不难,就一并列出 :

在这里插入图片描述

++以及 :

在这里插入图片描述

++以及关于本条目的子表里的行的修改,增删改查

在这里插入图片描述

++以及

在这里插入图片描述

(8)以下是关于列的增删

在这里插入图片描述

(9)至此,本 QStandardItem 的源码阅读完毕,给出完整的源代码,本类定义于头文件 qstandarditemmodel . h

//这是两个全局函数
Q_GUI_EXPORT QDataStream & operator>>(QDataStream & in ,       QStandardItem & item);
Q_GUI_EXPORT QDataStream & operator<<(QDataStream & out, const QStandardItem & item);

/*
The QStandardItem class provides an item for use with the QStandardItemModel class.

Detailed Description :
Items usually contain text, icons, or checkboxes. 项目通常包含文本、图标或复选框。

每个项目都可以有自己的背景画笔,这通过 setBackground()函数来设置。
当前的背景画笔可以通过 background()函数来获取。
每个项目的文本标签可以使用其特定的字体和画笔来呈现,
这通过`setFont()和`setForeground()、函数进行指定,并通过`font()`和`foreground()'函数来读取。
Each item can have its own background brush which is set with the
    setBackground() function.
The current background brush can be found with background().
The text label for each item can be rendered with its own font and brush.
These are specified with the setFont() and setForeground() functions,
and read with font() and foreground().

默认情况下,项目被启用,可编辑,可选取,可勾选,并且既可以作为拖放操作的源,也可以作为落点目标.
每个项目的标志可以通过调用 setFlags()函数来更改。
可勾选的项目可以通过调用`setCheckState(函数进行勾选和取消勾选。
相应的`checkState()、函数则指示该项目当前是否被勾选。
By default, items are enabled, editable, selectable, checkable,
and can be used both as the source of a drag and drop operation and as a drop target.
Each item's flags can be changed by calling setFlags().
Checkable items can be checked and unchecked with the setCheckState() function.
The corresponding checkState() function indicates whether the item is currently checked.

你可以通过调用setData()方法将特定应用程序的数据存储在项目中。
You can store application-specific data in an item by calling setData().

每个项目都可以有一个包含子项目的二维表格,这使得构建项目层次结构成为可能。
典型的层次结构是树状结构,在这种情况下,子表是一个具有单列(即列表)的表格
Each item can have a two-dimensional table of child items.
This makes it possible to build hierarchies of items.
The typical hierarchy is the tree,
in which case the child table is a table with a single column (a list).

子表的维度可以通过`setRowCount()、和'setColumnCount()来设置。
使用`setChild()、可以定位子表中的项。通过、child()、可以获取子项的指针。
此外,还可以通过和`insertColumn()'insertRow()来插入新的行和列,
或通过`appendRow()和appendcolumn()来追加行和列。
在使用`append`和`insert函数时,子表的维度会根据需要自动扩展。
The dimensions of the child table can be set with setRowCount() and setColumnCount().
Items can be positioned in the child table with setChild().
Get a pointer to a child item with child().
New rows and columns of children can also be inserted with insertRow() and insertColumn(),
 or appended with appendRow() and appendColumn().
When using the append and insert functions,
the dimensions of the child table will grow as needed.

通过调用`removeRow()、或`takeRow()、可以移除现有的行,
相应地,通过调用removeColumn()或`takeColumn()、可以移除列。
An existing row of children can be removed with removeRow() or takeRow();
correspondingly, a column can be removed with removeColumn() or takeColumn().

可以通过调用sortChildren()对项目的子项进行排序。
An item's children can be sorted by calling sortChildren().

Subclassing 继承本类,自定义条目时的指导: 
当子类化QStandardltem以提供自定义项目时,
可以为它们定义新类型,以便将它们与基类区分开.
来应重新实现 type()函数,以返回等于或大于 UserType 的新类型值。
When subclassing QStandardItem to provide custom items,
it is possible to define new types for them so that
    they can be distinguished from the base class.
The type() function should be reimplemented to
    return a new type value equal to or greater than UserType.

如果你想要对数据查询进行自定义处理和/或控制项目的数据表示方式,请重新实现data()和setData()。
Reimplement data() and setData() if you want to perform
    custom handling of data queries and/or control how an item's data is represented.

如果您希望QStandardltemModel能够按需创建自定义项目类的实例,
请重新实现clone()(参见QStandardltemModel::setltemPrototype())。
Reimplement clone() if you want QStandardItemModel to be able to
    create instances of your custom item class on demand
(see QStandardItemModel::setItemPrototype()).

如果你想控制项目在序列化形式中的表示方式,请重新实现read()和write()方法。
Reimplement read() and write() if you want to control
    how items are represented in their serialized form.

如果要控制项比较的语义,请重新实现operator<()。
operator<(.)确定使用 sortChildren()或
QStandardltemModel::sort()对项目进行排序时的排序顺序。
Reimplement operator<() if you want to control the
    semantics of item comparison.
operator<() determines the sorted order when sorting items with sortChildren(),
    or with QStandardItemModel::sort().

*/


class Q_GUI_EXPORT QStandardItem
{ 
protected:
    QStandardItem(const QStandardItem & other);             // copy构造函数
    QStandardItem & operator=(const QStandardItem & other); // copy赋值运算符函数

    QStandardItem(QStandardItemPrivate &   dd);             //有参构造函数

    QScopedPointer<QStandardItemPrivate> d_ptr;             //本类的数据成员

    void emitDataChanged(); //当本条目被修改时,调用此函数向表格模型发送 DataChanged信号
    //Causes the model associated with this item to
    //  emit a dataChanged() signal for this item.
    //You normally only need to call this function if you have subclassed QStandardItem
    //  and reimplemented data() and/or setData().

private:
    Q_DECLARE_PRIVATE(QStandardItem)
    friend class QStandardItemModelPrivate;                 //本类的两个友元类。
    friend class QStandardItemModel;

public:
    QStandardItem(); //默认构造函数

    explicit
    QStandardItem(                    const QString & text); //有参构造函数
    //测试表明,形参的 text会成为本条目的 dispalyRole = 0 属性,
    //  也会成为初始的 editRole = 2 属性的值,后者就可以接着被修改了。

    QStandardItem(const QIcon & icon, const QString & text); //有参构造函数

    explicit
    QStandardItem(int rows, int columns = 1);                //有参构造函数

    virtual ~QStandardItem(); //虚析构函数,以便于被继承

    virtual       //Qt::ItemDataRole::UserRole = 0x0100 这是最后一个预定义的角色枚举值
    QVariant      data(                        int role = Qt::UserRole + 1) const;

    virtual
    void     multiData(QModelRoleDataSpan          roleDataSpan) const;

    virtual
    void       setData(const QVariant & value, int role = Qt::UserRole + 1);

    void     clearData();

    inline QString        text()           const {  //Qt::DisplayRole     = 0
        return qvariant_cast<QString>(data(Qt::DisplayRole));
    }
    inline void        setText(const QString & text)
    {   setData(text, Qt::DisplayRole); }

    inline QIcon          icon()           const {  //Qt::DecorationRole  = 1
        return qvariant_cast<QIcon>(data(Qt::DecorationRole));
    }
    inline void        setIcon(const QIcon & icon)
    {   setData(icon, Qt::DecorationRole); }


    inline QString        toolTip()        const {  //Qt::ToolTipRole     = 3
        return qvariant_cast<QString>(data(Qt::ToolTipRole));
    }
    inline void        setToolTip(const QString & toolTip)
    {   setData(toolTip, Qt::ToolTipRole); }

    inline QString        statusTip()      const {  //Qt::StatusTipRole   = 4
        return qvariant_cast<QString>(data(Qt::StatusTipRole));
    }
    inline void        setStatusTip(const QString & statusTip)
    {   setData(statusTip, Qt::StatusTipRole); }

    inline QString        whatsThis()      const {  //Qt::WhatsThisRole   = 5
        return qvariant_cast<QString>(data(Qt::WhatsThisRole));
    }
    inline void        setWhatsThis(const QString & whatsThis)
    {   setData(whatsThis, Qt::WhatsThisRole); }

    inline QFont          font()           const {  //Qt::FontRole        = 6
        return qvariant_cast<QFont>(data(Qt::FontRole));
    }
    inline void        setFont(const QFont & font)
    {   setData(font, Qt::FontRole); }

    inline Qt::Alignment  textAlignment()  const {  //Qt::TextAlignmentRole  = 7
        return Qt::Alignment(qvariant_cast<int>(data(Qt::TextAlignmentRole)));
    }
    inline void        setTextAlignment(Qt::Alignment textAlignment)
    {   setData(int(textAlignment), Qt::TextAlignmentRole); }


    inline QBrush         background()     const {  //Qt::BackgroundRole     = 8
        return qvariant_cast<QBrush>(data(Qt::BackgroundRole));
    }
    inline void        setBackground(const QBrush & brush)
    {   setData(brush, Qt::BackgroundRole); }

    inline QBrush         foreground()     const {  //Qt::ForegroundRole     = 9
        return qvariant_cast<QBrush>(data(Qt::ForegroundRole));
    }
    inline void        setForeground(const QBrush & brush)
    {   setData(brush, Qt::ForegroundRole); }

    inline Qt::CheckState checkState()     const {  //Qt::CheckStateRole     = 10
        return Qt::CheckState(qvariant_cast<int>(data(Qt::CheckStateRole)));
    }
    inline void        setCheckState(Qt::CheckState checkState)
    {   setData(checkState, Qt::CheckStateRole); }

    inline QString        accessibleText() const {  //Qt::AccessibleTextRole = 11
        return qvariant_cast<QString>(data(Qt::AccessibleTextRole));
    }
    inline void        setAccessibleText(const QString & accessibleText)
    {   setData(accessibleText, Qt::AccessibleTextRole); }

    inline QString        accessibleDescription() const{//Qt::AccessibleDescriptionRole=12
        return qvariant_cast<QString>(data(Qt::AccessibleDescriptionRole));
    }
    inline void        setAccessibleDescription(const QString & accessibleDescription)
    {   setData(accessibleDescription, Qt::AccessibleDescriptionRole); }

    inline QSize          sizeHint()       const { //Qt::SizeHintRole       = 13
        return qvariant_cast<QSize>(data(Qt::SizeHintRole));
    }
    inline void        setSizeHint(const QSize & sizeHint)
    {   setData(sizeHint, Qt::SizeHintRole); }

//**********************************************************************************
//***************以上的成员函数时关于模型里条目里的角色数据的读取与设置**********************
//**********************************************************************************


//**********************************************************************************
//***************以下的成员函数时关于模型里条目里的操作属性的读取与设置**********************
//**********************************************************************************


/*
//这是本 Qt里模型与视图架构里的条目的属性。This enum describes the properties of an item。
//请注意,可检查项 checkable items 需要同时具备一组合适的标记和初始状态,以表明该项是否已检查。
//对于模型/视图组件,这是自动处理的,
//但对于QListWidgetltem、QTableWidgetltem 和 QTreeWidgetltem的实例,则需要进行显式设置。
enum ItemFlag { //这是描述 QTableWidget 表格等窗体中的条目的属性
    NoItemFlags          =   0, //It does not have any properties set.
    ItemIsSelectable     =   1, //It can be selected.
    ItemIsEditable       =   2, //It can be edited.
    ItemIsDragEnabled    =   4, //It can be dragged.
    ItemIsDropEnabled    =   8, //It can be used as a drop target.
    ItemIsUserCheckable  =  16, //可由用户更改复选状态
                                //It can be checked or unchecked by the user.
    ItemIsEnabled        =  32, //The user can interact with the item.
    ItemIsAutoTristate   =  64, //该项目的状态取决于其子项的状态。这使得在 QTreeWidget 中
        //可以自动管理父项的状态(如果所有子项均被选中,则父项也被选中 checked;
        //如果所有子项均未被选中,则父项未被选中 unchecked;
        //如果只有部分子项被选中,则父项处于部分选中状态 partially checked )。

    ItemNeverHasChildren = 128, //The item never has child items.
                                //This is used for optimization purposes only.

    ItemIsUserTristate   = 256  //The user can cycle through three separate states.
};
Q_DECLARE_FLAGS(ItemFlags, ItemFlag)     // ItemFlags = QFlags<ItemFlag>
Q_DECLARE_OPERATORS_FOR_FLAGS(ItemFlags) //这俩宏以完善对枚举量的运算定义
*/

    Qt::ItemFlags          flags() const;
    void                setFlags(Qt::ItemFlags flags);

    inline bool          isSelectable()   const { //ItemIsSelectable    =   1
        return (flags() & Qt::ItemIsSelectable) != 0;
    }                                           //都是在检测 Qt::ItemFlags 枚举类里的值
    void                setSelectable(bool selectable);

    inline bool          isEditable() const     { //ItemIsEditable      =   2
        return (flags() & Qt::ItemIsEditable) != 0;
    }
    void                setEditable(bool editable);

    inline bool          isDragEnabled()  const { //ItemIsDragEnabled   =   4
        return (flags() & Qt::ItemIsDragEnabled) != 0;
    }
    void                setDragEnabled(bool dragEnabled);

    inline bool          isDropEnabled()  const { //ItemIsDropEnabled   =   8
        return (flags() & Qt::ItemIsDropEnabled) != 0;
    }
    void                setDropEnabled(bool dropEnabled);

    inline bool          isCheckable()    const { //ItemIsUserCheckable =  16
        return (flags() & Qt::ItemIsUserCheckable) != 0;
    }
    void                setCheckable(bool checkable);

    inline bool          isEnabled()      const { //ItemIsEnabled       =  32
        return (flags() & Qt::ItemIsEnabled) != 0;
    }
    void                setEnabled(bool enabled);

    inline bool          isAutoTristate() const { //ItemIsAutoTristate  =  64
        return (flags() & Qt::ItemIsAutoTristate) != 0;
    }
    void                setAutoTristate(bool tristate);

    inline bool          isUserTristate() const { //ItemIsUserTristate  = 256
        return (flags() & Qt::ItemIsUserTristate) != 0;
    }
    void                setUserTristate(bool tristate);


//**********************************************************************************
//***********************以下是本条目的非角色与属性的成员函数*****************************
//**********************************************************************************


    //Returns the row / column where the item is located in its parent's child table,
    //  or -1 if the item has no parent.
    int                  row   () const; //看本条目位于哪一行
    int                  column() const; //看本条目位于那一列
    //Returns the QModelIndex associated with this item.
    //When you need to invoke item functionality in a QModelIndex-based API
    //(e.g. QAbstractItemView), you can call this function to obtain an index that
    //  corresponds to the item's location in the model.
    //If the item is not associated with a model, an invalid QModelIndex is returned.
    QModelIndex          index () const; //返回一个与本条目关联的模型索引

/*
class QModelIndex {      //对比一下与模型索引 QModelIndex 里同名同功能的成员函数
    int                  row       () { return r; }
    int                  column    () { return c; }
    quintptr             internalId() { return i; }
    QModelIndex          parent() const;
};
*/

    //Returns the QStandardItemModel that this item belongs to.
    //If the item is not a child of another item that belongs to the model,
    //  this function returns nullptr.
    QStandardItemModel * model  () const; //返回本条目所属的模型,   或 nullptr。
    //QObject * QObject::parent()         //本类并不是 QObject 的子类,所以可以这么定义。
    QStandardItem      * parent () const; //返回本条目的父条目的地址,或 nullptr。
    //Returns the item's parent item, or nullptr if the item has no parent.
    //Note: For toplevel items parent() returns nullptr.
    //To receive toplevel item's parent,
    //  use QStandardItemModel::invisibleRootItem() instead.


    virtual      //Returns a copy of this item. The item's children are not copied.
    QStandardItem      * clone() const;   //默认实现是浅拷贝,不 copy本条目的子条目。
    //When subclassing QStandardItem,
    //you can reimplement this function to provide QStandardItemModel with a
    //  factory that it can use to create new items on demand.
    //当子类化QStandardltem时,您可以重新实现此函数,以为QStandardltemMode!提供一个工厂,
    //该工厂可用于按需创建新项目。

    enum ItemType { Type = 0, UserType = 1000 };
    virtual int          type () const;
    //返回此项目的类型。该类型用于区分自定义项目与基类。
    //在子类化 QStandardltem 时,应重写此函数并返回一个大于或等于 UserType 的新值。
    //Returns the type of this item.
    //The type is used to distinguish custom items from the base class.
    //When subclassing QStandardItem, you should reimplement this function and
    //  return a new value greater than or equal to UserType.

    //Reads the item from stream in.(Writes the item to stream out. )。
    //Only the data and flags of the item are read / written, not the child items.
    virtual void         read (QDataStream & in )      ; //从数据流里读数据,但不包含子类的数据
    virtual void         write(QDataStream & out) const; //写本条目的数据到数据流

    virtual bool operator< (const QStandardItem & other) const; //无注释

//**********************************************************************************
//*********************以下当本条目又是二维表时的操作子表的成员函数************************
//**********************************************************************************

    //这几个成员函数说明,本表格里的条目,还可以包含二维表,估计是借此构成树型 model。
    //Returns the number of child item rows / columns that the item has.
    int      rowCount   () const     ; //返回本条目包含的二维表的行数。
    int      columnCount() const     ; //返回本条目包含的二维表的列数。
    void  setRowCount   (int rows   ); //重新设置本条目包含的二维表的行数
    void  setColumnCount(int columns); //重新设置本条目包含的二维表的列数。
    //Sets the number of child item rows(columns) to rows(columns).
    //If this is less than rowCount() / columnCount(),
    //  the data in the unwanted rows / columns is discarded.


    //Returns true if this item has any children; otherwise returns false.
    bool             hasChildren() const;   //判断本条目是否有子表。
    void            sortChildren(int column, Qt::SortOrder order = Qt::AscendingOrder);
    // enum Qt::SortOrder {AscendingOrder, DescendingOrder }; //按本子表的形参列进行排序
    //Sorts the children of the item using the given order,
    //  by the values in the given column.

    //Returns the child item at (row, column) if one has been set;
    //  otherwise returns nullptr. 返回本条目里的子表里的元素 [row, column]。
    QStandardItem *     child(int row, int column = 0) const;
    void             setChild(int row, int column, QStandardItem * item); //填充子表里的元素
    //Sets the child item at (row, column) to item.
    //This item (the parent item) takes ownership of item.
    //If necessary, the row count and column count are increased to fit the item.
    //Note: Passing nullptr as item removes the item.
    inline
    void             setChild(int row,             QStandardItem * item)  //函数重载
    {   setChild(row, 0, item); } //设置为本行的第一个元素。

    QStandardItem * takeChild(int row, int column = 0); //删除坐标[r,c]处的元素并返回之。
    //Removes the child item at (row, column) without deleting it,
    //  and returns a pointer to the item. If there was no child at the given location,
    //  then this function returns nullptr.
    //Note that this function, unlike takeRow() and takeColumn(),
    //  does not affect the dimensions of the child table.


    //Inserts a row at row containing items.
    //If necessary, the column count is increased to the size of items.
    //在行 row处插入一行,此行包含形参列表 items里的几个元素。
    void insertRow (int row, const QList<QStandardItem *> & items);
    inline //在行 row处插入一行,但此行只包含一个元素,在第一列,为 item。
    void insertRow (int row,             QStandardItem *    item)
    { insertRow(arow, QList<QStandardItem*>() <<  item); }
    //Inserts a row at row containing item.
    //When building a list or a tree that has only one column,
    //  this function provides a convenient way to insert a single new item.

    //Inserts items at row. The column count won't be changed.
    //本表的列数不变,从而构成插入多行,若形参 items里包含的元素太多。
    void insertRows(int row, const QList<QStandardItem *> & items);
    void insertRows(int row, int count); //在行 row处插入 count行,但这些行都为空。
    //Inserts count rows of child items at row row.

    inline void appendRow (QStandardItem * item) //Appends a row containing item.
    {   insertRow (rowCount(), item ); }         //在本表的末尾增加一行,只包含形参 item一个元素。

    inline void appendRow (const QList<QStandardItem *> & items)
    {   insertRow (rowCount(), items); } //在本表的末尾增加一行,必要时增加列数。
    //Appends a row containing items.
    //If necessary, the column count is increased to the size of items.

    inline void appendRows(const QList<QStandardItem *> & items)
    {   insertRows(rowCount(), items); } //增加行的时候,固定列数
    //Appends rows containing items. The column count will not change.

    //Removes the given row. The items that were in the row are deleted.
    void removeRow (int row);            //删除形参指定的行
    void removeRows(int row, int count); //删除形参 row处的 count行条目。
    //Removes count rows at row row. The items that were in those rows are deleted.
    
    QList<QStandardItem *> takeRow(int row);     //删除第 row行条目并返回。
    //Removes row without deleting the row items,
    //  and returns a list of pointers to the removed items.
    //For items in the row that have not been set,
    //  the corresponding pointers in the list will be nullptr.
    
    //Inserts a column at column containing items.在 column处插入一列,必要时扩展表的行数。
    //If necessary, the row count is increased to the size of items.
    void insertColumn (int column, const QList<QStandardItem *> & items);
    void insertColumns(int column, int count);  //在列 column处插入 count列。
    //Inserts count columns of child items at column column.
    
    inline  //在本表的最后增加一列,并填充元素,必要时扩充行。
    void appendColumn (const QList<QStandardItem *> & items)
    {   insertColumn(columnCount(), items); }
    //Appends a column containing items.
    //If necessary, the row count is increased to the size of items.
    
    //Removes the given column. The items that were in the column are deleted.
    void removeColumn (int column);            //删除第 column列,清除该列里的元素。
    void removeColumns(int column, int count); //删除 column开始的 count列元素。
    //Removes count columns at column column.
    //The items that were in those columns are deleted.
    
    QList<QStandardItem *> takeColumn(int column); //删除第 column列并返回该列的元素。
    //Removes column without deleting the column items,
    //  and returns a list of pointers to the removed items.
    //For items in the column that have not been set,
    //  the corresponding pointers in the list will be nullptr.

}; //完结 class QStandardItem


(10)本类的内容很多,但理解起来不难的。

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangzhangkeji

谢谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值