(14)本源代碼定義于頭文件 qtablewidget . h 頭文件 :
#ifndef QTABLEWIDGET_H
#define QTABLEWIDGET_H#include <QtWidgets/qtableview.h>
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtCore/qlist.h>
#include <QtCore/qvariant.h>QT_REQUIRE_CONFIG(tablewidget);QT_BEGIN_NAMESPACEclass QTableWidgetSelectionRange
{
public:QTableWidgetSelectionRange() = default;QTableWidgetSelectionRange(int top, int left, int bottom, int right): m_top(top), m_left(left), m_bottom(bottom), m_right(right){}inline int topRow() const { return m_top; }inline int bottomRow() const { return m_bottom; }inline int leftColumn() const { return m_left; }inline int rightColumn() const { return m_right; }inline int rowCount() const { return m_bottom - m_top + 1; }inline int columnCount() const { return m_right - m_left + 1; }
private:int m_top = -1, m_left = -1, m_bottom = -2, m_right = -2;
};class QTableWidget;
class QTableModel;
class QWidgetItemData;
class QTableWidgetItemPrivate;/*
The QTableWidgetItem class provides an item for use with the QTableWidget class.Detailed Description :
表格項用于存儲表格小部件的信息。項目通常包含文本、圖標或復選框。
QTableWidgetltem類是一個方便的類,它在Qt 3中替換了QTableWidgetltem類。
它提供了一個可以與QTableWidgetltem類一起使用的項目。
頂級項目在沒有父項的情況下構建,然后根據行號和列號指定的位置插入:QTableWidgetItem * newItem = new QTableWidgetItem(tr("%1").arg(pow(row, column+1)));tableWidget->setItem(row, column, newItem);每個項目都可以有自己的背景畫筆,這通過`setBackground()、函數來設置。
當前的背景畫筆可以通過background ()、函數來獲取。
每個項目的文本標簽可以使用其特定的字體和畫筆來呈現,這通過`setFont ()'和setForeground)函數進行指定,
并通過`font()`和`foreground()'函數來讀取。默認情況下,項是啟用的,可編輯的,可選擇的,可檢查的,并且既可以作為拖放操作的源,也可以作為落點目標。
每個項的標記可以通過調用setFlags()函數并傳入相應的值(見Qt:ItemFlags)來更改。
可檢查的項可以通過setCheckState()函數進行檢查和取消檢查。
對應的checkState()函數則指示該項當前是否被檢查過。Subclassing :
當子類化 QTableWidgetltem 以提供自定義項時,可以為它們定義新類型,以便它們可以與標準項區分開來.
需要此功能的子類的構造函數需要使用等于或大于 UserType 的新類型值調用基類構造函數。*/class Q_WIDGETS_EXPORT QTableWidgetItem
{friend class QTableWidget;friend class QTableModel;
private:QTableModel * tableModel() const;private: //可見,表格里的條目還有豐富的數據成員,以描述條目里的數據與屬性int rtti ;QList<QWidgetItemData> values ; //包含了條目里的數據QTableWidget * view ; //本條目屬于哪個表格窗體。QTableWidgetItemPrivate * d ;Qt::ItemFlags itemFlags; //本條目的編輯屬性。public:enum ItemType { Type = 0, UserType = 1000 };//Constructs a table item of the specified type that does not belong to any table.//形參 type會賦值給本類的私有數據成員 rtti,以保存本條目的類型。explicit QTableWidgetItem(int type = Type); //默認類型是 0inline int type() const { return rtti; }//Returns the type passed to the QTableWidgetItem constructor.//Constructs a table item with the given text.explicit QTableWidgetItem(const QString & text, int type = Type); //有參構造函數explicit QTableWidgetItem(const QIcon & icon,const QString & text, int type = Type);QTableWidgetItem(const QTableWidgetItem & other); //copy構造函數QTableWidgetItem & operator=(const QTableWidgetItem & other);//copy賦值運算符函數virtual ~QTableWidgetItem(); //析構函數virtual bool operator< (const QTableWidgetItem & other) const; //無注釋virtual QTableWidgetItem * clone() const; //Creates a copy of the item.//Returns the table widget that contains the item.inline QTableWidget * tableWidget() const { return view; }inline int row () const{ return (view ? view->row(this) : -1); }inline int column() const{ return (view ? view->column(this) : -1); }//Returns the row of the item in the table.//If the item is not in a table, this function will return -1.virtual void read (QDataStream & in ) ; //Reads the item from stream in .virtual void write(QDataStream & out) const; //Writes the item to stream out.//Returns true if the item is selected, otherwise returns false.bool isSelected() const;void setSelected(bool select); //Sets the selected state of the item to select./*enum Qt::ItemFlag {NoItemFlags = 0,ItemIsSelectable = 1,ItemIsEditable = 2,ItemIsDragEnabled = 4,ItemIsDropEnabled = 8,ItemIsUserCheckable = 16,ItemIsEnabled = 32,ItemIsAutoTristate = 64,ItemNeverHasChildren = 128,ItemIsUserTristate = 256};Q_DECLARE_FLAGS(ItemFlags, ItemFlag)Q_DECLARE_OPERATORS_FOR_FLAGS(ItemFlags)*/inlineQt::ItemFlags flags() const { return itemFlags; } //返回條目具有的屬性void setFlags(Qt::ItemFlags flags);virtual QVariant data(int role) const; //讀寫條目里具有的數據。virtual void setData(int role, const QVariant &value);//以下依次是讀寫條目里各角色對應的數據。inline QString text() const //角色 0{ return data(Qt::DisplayRole).toString(); }inline void setText(const QString & text){ setData(Qt::DisplayRole, text); }inline QIcon icon() const //角色 1{ return qvariant_cast<QIcon>(data(Qt::DecorationRole)); }inline void setIcon(const QIcon & icon){ setData(Qt::DecorationRole, icon); }inline QString toolTip() const //角色 3{ return data(Qt::ToolTipRole).toString(); }inline void setToolTip(const QString & toolTip){ setData(Qt::ToolTipRole, toolTip); }inline QString statusTip() const //角色 4{ return data(Qt::StatusTipRole).toString(); }inline void setStatusTip(const QString &statusTip){ setData(Qt::StatusTipRole, statusTip); }inline QString whatsThis() const //角色 5{ return data(Qt::WhatsThisRole).toString(); }inline void setWhatsThis(const QString & whatsThis){ setData(Qt::WhatsThisRole, whatsThis); }inline QFont font() const //角色 6{ return qvariant_cast<QFont>(data(Qt::FontRole)); }inline void setFont(const QFont & font){ setData(Qt::FontRole, font); }inline int textAlignment() const//角色 7{ return data(Qt::TextAlignmentRole).toInt(); }inline void setTextAlignment(int alignment){ setData(Qt::TextAlignmentRole, alignment); }inline QBrush background() const //角色 8{ return qvariant_cast<QBrush>(data(Qt::BackgroundRole)); }inline void setBackground(const QBrush & brush){ setData(Qt::BackgroundRole,brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }//QBrush(Qt::GlobalColor color, Qt::BrushStyle bs = Qt::SolidPattern);inline QBrush foreground() const //角色 9{ return qvariant_cast<QBrush>(data(Qt::ForegroundRole)); }inline void setForeground(const QBrush &brush){ setData(Qt::ForegroundRole,brush.style() != Qt::NoBrush ? QVariant(brush) : QVariant()); }inline //enum Qt::CheckState { Unchecked, PartiallyChecked, Checked };Qt::CheckState checkState() const //角色 10{ return static_cast<Qt::CheckState>(data(Qt::CheckStateRole).toInt()); }inlinevoid setCheckState(Qt::CheckState state){ setData(Qt::CheckStateRole, state); }inline QSize sizeHint() const //角色 13{ return qvariant_cast<QSize>(data(Qt::SizeHintRole)); }inline void setSizeHint(const QSize & size){ setData(Qt::SizeHintRole, size.isValid() ? QVariant(size) : QVariant()); }}; //完結 class QTableWidgetItem#ifndef QT_NO_DATASTREAMQ_WIDGETS_EXPORT QDataStream & operator>>(QDataStream &in , QTableWidgetItem &item);
Q_WIDGETS_EXPORT QDataStream & operator<<(QDataStream &out, const QTableWidgetItem &item);#endifclass QTableWidgetPrivate;/*
The QTableWidget class provides an item-based table view with a default model.Detailed Description :
表格小部件為應用程序提供標準的表格顯示功能。QTableWidgetltem中的項目由 QTableWidgetltem 提供。如果你想使用自己的數據模型來創建表格,你應該使用QTableView而不是這個類。表格小部件可以使用所需數量的行和列進行構建:tableWidget = new QTableWidget(12, 3, this);Alternatively, tables can be constructed without a given size and resized later:tableWidget = new QTableWidget(this);tableWidget->setRowCount(10);tableWidget->setColumnCount(5);項目在表之外創建(沒有父控件)并使用設置方法插入到表中。QTableWidgetItem * newItem = new QTableWidgetItem(tr("%1").arg((row+1)*(column+1)));tableWidget->setItem(row, column, newItem);如果您想在表格控件中啟用排序功能,詳細信息,請參閱setltem()方法.
請在填充內容后執行此操作,否則排序可能會影響插入順序.表格可以同時擁有橫向和縱向標題。創建標題的最簡單方法是向`setHorizontalHeaderLabels()和
`setVerticalHeaderLabels('函數提供一系列字符串。
這些函數將為表格的列和行提供簡單的文本標題。
更復雜的標題可以由現有的表格項生成,而這些表格項通常是在表格之外構建的。
例如,我們可以構建一個帶有圖標和對齊文本的表格項,并將其用作特定列的標題:QTableWidgetItem *cubesHeaderItem = new QTableWidgetItem(tr("Cubes"));cubesHeaderItem->setIcon(QIcon(QPixmap(":/Images/cubed.png")));cubesHeaderItem->setTextAlignment(Qt::AlignVCenter);The number of rows in the table can be found with rowCount(),
and the number of columns with columnCount().
The table can be cleared with the clear() function.
表格中的行數可以通過rowCount()找到,列數通過columncount()找到。
表格可以通過clear()函數清空。*/class Q_WIDGETS_EXPORT QTableWidget : public QTableView
{Q_OBJECT//This property holds the number of columns / rows in the table.//By default, for a table constructed without row and column counts,// this property contains a value of 0.Q_PROPERTY(int rowCount READ rowCount WRITE setRowCount)Q_PROPERTY(int columnCount READ columnCount WRITE setColumnCount)friend class QTableModel; //這是 Qt3 里的老類,已被模型視圖架構替代了。注釋文檔里這么說的。private:void setModel(QAbstractItemModel * model) override; //私有,不再被調用了。Q_DECLARE_PRIVATE(QTableWidget)Q_DISABLE_COPY(QTableWidget)Q_PRIVATE_SLOT(d_func(), void _q_sort())Q_PRIVATE_SLOT(d_func(), void _q_emitItemEntered (const QModelIndex & index))Q_PRIVATE_SLOT(d_func(), void _q_emitItemPressed (const QModelIndex & index))Q_PRIVATE_SLOT(d_func(), void _q_emitItemClicked (const QModelIndex & index))Q_PRIVATE_SLOT(d_func(), void _q_emitItemDoubleClicked (const QModelIndex & index))Q_PRIVATE_SLOT(d_func(), void _q_emitItemActivated (const QModelIndex & index))Q_PRIVATE_SLOT(d_func(), void _q_emitItemChanged (const QModelIndex & index))Q_PRIVATE_SLOT(d_func(), void _q_emitCurrentItemChanged(const QModelIndex & previous,const QModelIndex & current))Q_PRIVATE_SLOT(d_func(), void _q_dataChanged (const QModelIndex & topLeft,const QModelIndex & bottomRight))public://Creates a new table view with the given parent.explicitQTableWidget( QWidget * parent = nullptr); //有參構造函數QTableWidget(int rows, int columns, QWidget * parent = nullptr); //有參構造函數//Creates a new table view with the given rows and columns, and with the given parent.~QTableWidget(); //析構函數//Q_PROPERTY(int rowCount READ rowCount WRITE setRowCount)int rowCount() const;void setRowCount(int rows);//Q_PROPERTY(int columnCount READ columnCount WRITE setColumnCount)int columnCount() const;void setColumnCount(int columns);/* 這是表格窗體視圖的基類表格視圖里的構建表頭的代碼方法。
class QTableView : public QAbstractItemView
{
public :QHeaderView * horizontalHeader() const;void setHorizontalHeader(QHeaderView * header);QHeaderView * verticalHeader () const;void setVerticalHeader (QHeaderView * header);
}
*///Returns the horizontal header item for column, column, if one has been set;// otherwise returns nullptr.QTableWidgetItem * horizontalHeaderItem(int column) const;void setHorizontalHeaderItem(int column, QTableWidgetItem * item);//Sets the horizontal header item for column column to item.//If necessary, the column count is increased to fit the item.//The previous header item (if there was one) is deleted.之前的舊標題元素會被刪除。QTableWidgetItem * takeHorizontalHeaderItem(int column);//Removes the horizontal header item at column from the header without deleting it.QTableWidgetItem * verticalHeaderItem(int row) const;void setVerticalHeaderItem(int row, QTableWidgetItem * item);QTableWidgetItem * takeVerticalHeaderItem(int row);//Sets the vertical header labels using labels.void setVerticalHeaderLabels(const QStringList & labels);void setHorizontalHeaderLabels(const QStringList & labels);//Returns the item for the given row and column if one has been set;// otherwise returns nullptr.QTableWidgetItem * item(int row, int column) const;void setItem(int row, int column, QTableWidgetItem * item);//Sets the item for the given row and column to item.//表格接管了該項的所有權。//請注意,如果已啟用排序(參見`sortingEnabled`),且列是當前排序列,// 則該行將被移動到由`item`確定的已排序位置。//如果您想設置某一行中的多個項(例如,通過循環調用setltem()),可能需要在操作前關閉排序功能,//然后在操作后重新開啟;這樣您就可以為同一行中的所有項使用相同的行參數(即,setltem()不會移動該行)。QTableWidgetItem * takeItem(int row, int column);//Removes the item at row and column from the table without deleting it.//Returns a list of pointers to the items contained in the data object.//If the object was not created by a QTreeWidget in the same process, the list is empty.QList<QTableWidgetItem *> items(const QMimeData * data) const;//Returns the row / column for the item.int row(const QTableWidgetItem * item) const;int column(const QTableWidgetItem * item) const;//Returns the QModelIndex associated with the given item.條目索引與指針之間的相互轉換。QModelIndex indexFromItem (const QTableWidgetItem * item ) const;QTableWidgetItem * itemFromIndex(const QModelIndex & index) const;//Returns a pointer to the QTableWidgetItem associated with the given index.//Returns the row / Column of the current item.int currentRow () const;int currentColumn() const;QTableWidgetItem * currentItem () const;void setCurrentItem(QTableWidgetItem * item); //以代碼的方式選擇條目。//Sets the current item to item.//Unless the selection mode is NoSelection, the item is also selected.void setCurrentItem(QTableWidgetItem * item,QItemSelectionModel::SelectionFlags command);void setCurrentCell(int row, int column); //直接用行列下標設定條目void setCurrentCell(int row, int column, //這樣更好。QItemSelectionModel::SelectionFlags command);bool isSortingEnabled() const; //默認,表格排序是被禁止的。void setSortingEnabled(bool enable); //無注釋void sortItems(int column, Qt::SortOrder order = Qt::AscendingOrder);//Sorts all the rows in the table widget based on column and order.//按某列排序,影響的不僅僅本列,而是所有的行。整行都因為某列的排序而移動了。int visualRow (int logicalRow ) const; //返回邏輯索引與視覺索引的對應關系int visualColumn(int logicalColumn) const; //隱藏并不會改變視覺索引。//Returns the widget displayed in the cell in the given row and column.//Note: The table takes ownership of the widget.//測試說明,這個窗體組件,不屬于表中元素,不是先天就存在的。未設置前,是 nullptr。QWidget * cellWidget(int row, int column) const;void setCellWidget(int row, int column, QWidget * widget);inline //Removes the widget set on the cell indicated by row and column.void removeCellWidget(int row, int column){ setCellWidget(row, column, nullptr); }QList<QTableWidgetItem *> selectedItems () const; //處理多選用這個就夠//Returns a list of all selected ranges.QList<QTableWidgetSelectionRange> selectedRanges() const;void setRangeSelected(const QTableWidgetSelectionRange & range, bool select);//Selects or deselects the range depending on select.//QModelIndex QAbstractItemView::indexAt(const QPoint & point)基類里還有這個成員函數//Returns a pointer to the item at the given point,// or returns nullptr if point is not covered by an item in the table widget.QTableWidgetItem * itemAt(const QPoint & p) const;inlineQTableWidgetItem * itemAt(int x, int y) const //采用了表格自己的坐標系。{ return itemAt(QPoint(x, y)); }//Returns the item at the position equivalent to QPoint(ax, ay) in the// table widget's coordinate system,QList<QTableWidgetItem *> findItems(const QString & text, Qt::MatchFlags flags) const;//Finds items that matches the text using the given flags./*//This enum describes the type of matches that can be// used when searching for items in a model.enum Qt::MatchFlag { //本枚舉量用于組合框的條目搜索。本枚舉量指定了搜索方式MatchExactly = 0, //Performs QVariant-based matching.MatchContains = 1, //The search term is contained in the item.MatchStartsWith = 2, //The search term matches the start of the item.MatchEndsWith = 3, //The search term matches the end of the item.MatchRegularExpression = 4,MatchWildcard = 5,MatchFixedString = 8,MatchTypeMask = 0x0F,MatchCaseSensitive = 16, //The search is case sensitive.MatchWrap = 32,MatchRecursive = 64 //Searches the entire hierarchy.};Q_DECLARE_FLAGS(MatchFlags, MatchFlag)Q_DECLARE_OPERATORS_FOR_FLAGS(MatchFlags)*/const //Returns the item prototype used by the table.QTableWidgetItem * itemPrototype() const; //似乎在繼承 QTableWidgetltem時才用得上void setItemPrototype(const QTableWidgetItem *item);// Sets the item prototype for the table to the specified item.//該表格小部件在需要創建新的表格項時,將使用項原型克隆函數。//例如,當用戶在空單元格中進行編輯時。這非常有用,//尤其是在您有 QTableWidgetltem 子類并且希望確保 QTableWidget 創建您的子類實例的情況下。//表格接管原型的所有權。//返回某個單元格的位置信息QRect visualItemRect(const QTableWidgetItem * item) const; //無注釋using QAbstractItemView::isPersistentEditorOpen;/*class QAbstractItemView {bool isPersistentEditorOpen(const QModelIndex & index) const;void openPersistentEditor (const QModelIndex & index);void closePersistentEditor (const QModelIndex & index);}*///Returns whether a persistent editor is open for item item.bool isPersistentEditorOpen(QTableWidgetItem * item) const; //函數重載,參數類型不一樣//Starts editing the item if it is editable.void editItem (QTableWidgetItem * item); //打開的是普通易失編輯框void openPersistentEditor (QTableWidgetItem * item); //打開持久型編輯框//Opens an editor for the give item. The editor remains open after editing.void closePersistentEditor (QTableWidgetItem * item); //只有調用本函數才可以關閉持久框//Closes the persistent editor for item.protected:bool event(QEvent * e ) override;void dropEvent(QDropEvent * event) override;virtual QStringList mimeTypes() const;virtual QMimeData * mimeData(const QList<QTableWidgetItem *> & items) const;virtual bool dropMimeData(int row, int column,const QMimeData * data, Qt::DropAction action);virtual Qt::DropActions supportedDropActions() const;//Returns the drop actions supported by this view./*enum Qt::DropAction { //本枚舉類用于描述模型視圖里的拖動操作的語義:復制、剪切或超鏈接。CopyAction = 0x 1, //Copy the data to the target.MoveAction = 0x 2, //Move the data from the source to the target.LinkAction = 0x 4, //Create a link from the source to the target.ActionMask = 0x ff,TargetMoveAction = 0x8002, //在 Windows上,當 D&D數據的所有權應被目標應用程序接管時,//即源應用程序不應刪除這些數據時,會使用此值。//在X11上,此值用于執行移動操作。Mac上不使用TargetMoveAction。IgnoreAction = 0x 0 //Ignore the action (do nothing with the data).};Q_DECLARE_FLAGS(DropActions, DropAction)Q_DECLARE_OPERATORS_FOR_FLAGS(DropActions)*/public Q_SLOTS://Scrolls the view if necessary to ensure that the item is visible.//The hint parameter specifies more precisely where the// item should be located after the operation.void scrollToItem(const QTableWidgetItem * item,QAbstractItemView::ScrollHint hint = EnsureVisible);/*enum QAbstractItemView::ScrollHint {EnsureVisible , //Scroll to ensure that the item is visible.PositionAtTop , //Scroll to position the item at the top of the viewport.PositionAtBottom, //Scroll to position the item at the bottom of the viewport.PositionAtCenter //Scroll to position the item at the center of the viewport.};Q_ENUM(ScrollHint) //滾動屏幕到條目 index處,并指明了 index條目的新的位置virtual void QAbstractItemView::scrollTo(const QModelIndex & index,ScrollHint hint = EnsureVisible) = 0;*///Inserts an empty row into the table at row.void insertRow (int row ); //在行 row ,列 column處插入一行或一列。void insertColumn(int column);void removeRow(int row);void removeColumn(int column); //刪除第 row行或第 column列。//Removes the column column and all its items from the table.//Removes all items in the view. This will also remove all selections and headers.//If you don't want to remove the headers, use QTableWidget::clearContents().//The table dimensions stay the same.void clear (); //行列框架 還會保存,表頭數據沒有了,改成了123數字void clearContents(); //行列框架和表頭數據都會保存,只清除表體中的數據,置為空。//Removes all items not in the headers from the view.//This will also remove all selections. The table dimensions stay the same.Q_SIGNALS:void itemEntered(QTableWidgetItem * item);void cellEntered(int row, int column);void itemPressed(QTableWidgetItem * item);void cellPressed(int row, int column);void itemClicked(QTableWidgetItem * item);void cellClicked(int row, int column);//This signal is emitted when the specified item has been activatedvoid itemActivated(QTableWidgetItem * item);void cellActivated(int row, int column);void itemDoubleClicked(QTableWidgetItem * item);void cellDoubleClicked(int row, int column);//This signal is emitted whenever the data of item has changed.void itemChanged(QTableWidgetItem * item); //當條目里的數據改變時,觸發本信號void cellChanged(int row, int column);//This signal is emitted whenever the current item changes.//The previous item is the item that previously had the focus,// current is the new current item. //當焦點切換時觸發本信號函數。// 經測試發現,本信號函數里的 previous 形參不要使用。否則程序會閃退。void currentItemChanged(QTableWidgetItem * current, QTableWidgetItem * previous);void currentCellChanged(int currentRow, int currentColumn,int previousRow, int previousColumn);void itemSelectionChanged(); //當焦點選擇變化時觸發本信號,但沒有形參。//This signal is emitted whenever the selection changes.}; //完結 class QTableWidget : public QTableViewQT_END_NAMESPACE#endif // QTABLEWIDGET_H
(15)
謝謝