Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic operation and use of Qt QTableWidget

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail about the basic operation and use of Qt QTableWidget, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

QTableWidget is a table component class in Qt. After placing a QTableWidget component on the form, you can set its properties in Property Editor, and double-click the component to open an editor to edit its Colum, Row, and Item.

The basic interface structure of a QTableWidget component is shown in figure 1, and the table is set to 6 rows and 5 columns.

Figure 1 the basic structure of an QTableWidget table and the row and column index numbers of the workspace

The first row of the table is called the row header, which is used to set the title of each column, and the first column is called the column header, and you can set its title, but generally use the default title, that is, the row number. Row and column headers are generally not editable.

The table area except the row and column headers is the content area, and the content area is a regular grid, like a two-dimensional array, and each grid cell is called a cell. Each cell has a row number and a column number, and figure 1 shows the change rule of the row number and column number.

In the QTableWidget table, each cell is a QTable Widgetltem object that can set text content, font, foreground color, background color, icon, edit and display tags. Each cell can also store one QVariant data, which is used to set up user-defined data.

Figure 2 Runtime interface of an example Samp4_9

The example samp4_9 takes QTableWidget as the main component to demonstrate the implementation of some major operations of QTableWidget. The run-time interface of the instance is shown in figure 2, which demonstrates how to implement the following functions:

Set the number of columns and rows of the table, set the text of the header, format, and so on.

Initialize the table data and set up a batch of instance data to populate the table.

The operation of inserting rows, adding rows, and deleting the current row.

Iterate through all the cells of the table, read the contents of the table into a QPlainTextEdit, and one row of data in the table as one line of text.

When the current cell selected on the table changes, the information stored in the cell is displayed in the status bar.

Interface design and initialization

The main form of Samp4_9 inherits from QMainWindow. On the window shown in figure 2, a QTableWidget component and a QPlainTextEdit component form a split layout splitter up and down. The buttons on the left are placed in a QGroupBox component, using the Grid layout, and then the groupBox and splitter are divided left and right. This is a typical layout of three-zone division.

Some variables and functions are customized in the main window class MainWindow, which are used in the following code implementation. Here are the variables and functions customized in the private section of MainWindow:

Private: / / customize the type of cell Type, using enum CellType {ctName=1000,ctSex,ctBirth,ctNation,ctPartyM,ctScore} when creating the item of the cell; / / column number enum FieldColNum {colName=0,colSex,colBirth,colNation,colScore,colPartyM} of each field in the table; QLabel * labCellIndex; / / status bar to display the cell's row number, column number QLabel * labCellType; / / type QLabel * labStudID used to display the cell on the status bar / / the status bar is used to display the student ID void createItemsARow (int rowNo,QString Name,QString Sex,QDate birth,QString Nation,bool isPM,int score); / / create an items for a row

The enumeration type CellType is used to represent cell types and is used when creating cells. The enumeration type FieldColNum uses enumeration constants to represent the column numbers of each field in the table.

Initialize the interface in the constructor of MainWindow, as follows:

MainWindow::MainWindow (QWidget * parent): QMainWindow (parent), ui (new Ui::MainWindow) {ui- > setupUi (this); setCentralWidget (ui- > splitterMain); / / status bar initialization creates labCellIndex = new QLabel ("current cell coordinates:", this); labCellIndex- > setMinimumWidth; labCellType=new QLabel ("current cell type:", this); labCellType- > setMinimumWidth (200); labStudID=new QLabel ("Student ID:", this) LabStudID- > setMinimumWidth; ui- > statusBar- > addWidget (labCellIndex); / / add to the status bar ui- > statusBar- > addWidget (labCellType); ui- > statusBar- > addWidget (labStudID);} QTableWidget basic Operation Settings header

The "set header" button on the interface realizes the setting of the header. The slot function code of the clicked () signal is as follows:

LabStudID- > setMinimumWidth; ui- > statusBar- > addWidget (labCellIndex); / / add to the status bar ui- > statusBar- > addWidget (labCellType); ui- > statusBar- > addWidget (labStudID);}

The text headings of each column in the row header are initialized and stored by a QStringList object headerText. If you just set the title of each column in the row header, you can use the following statement:

Ui- > tableInfo- > setHorizontalHeaderLabels (headerText)

If you need more specific formatting, you need to create a variable of type QTableWidgetItem for each cell in the row header and set it accordingly.

In a table, each cell is a QTableWidgetItem object, whether it's a header or a workspace. The QTableWidgetItem object stores all the contents of the cell, including the word title, formatting, and associated data. The for loop in the above program iterates through each line of headerText, creates a QTableWidgetItem object headerltem with each line of text, sets the font size of headerItem to 12, bold, and red, and assigns headerltem to a column in the header:

Ui- > tableInfo- > setHorizontalHeaderItern (I, headerItem); initialize table data

The "initialize Table data" button on the interface generates a data fill table based on the number of rows in the table, generates a QTableWidgetItem object for each cell, and sets the corresponding properties. The following is the slot function code of btnlniData's clicked () signal:

Else icon.addFile (": / images/icons/girl.ico"); item=new QTableWidgetItem (Sex,MainWindow::ctSex); / / create a new Item and set the cell type to custom MainWindow::ctSex item- > setIcon (icon); item- > setTextAlignment (Qt::AlignHCenter | Qt::AlignVCenter); / / set Item ui- > tableInfo- > setItem (rowNo,MainWindow::colSex,item) for the cell / / set Item / / birth date str=birth.toString ("yyyy-MM-dd") for the cell; / / convert the date to the string item=new QTableWidgetItem (str,MainWindow::ctBirth); / / create a new Item and set the cell type to custom MainWindow::ctBirth item- > setTextAlignment (Qt::AlignLeft | Qt::AlignVCenter); / / text alignment format ui- > tableInfo- > setItem (rowNo,MainWindow::colBirth,item) / / set Item / / ethnic item=new QTableWidgetItem (Nation,MainWindow::ctNation) for the cell; / / create a new Item, and set the cell type to custom MainWindow::ctNation item- > setTextAlignment (Qt::AlignHCenter | Qt::AlignVCenter); / / text alignment format ui- > tableInfo- > setItem (rowNo,MainWindow::colNation,item); / / set Item / / whether or not item=new QTableWidgetItem (Party member, MainWindow::ctPartyM) for the cell / / create a new Item and set the cell type to custom MainWindow::ctPartyM item- > setTextAlignment (Qt::AlignHCenter | Qt::AlignVCenter); / / text alignment format if (isPM) item- > setCheckState (Qt::Checked); else item- > setCheckState (Qt::Unchecked); item- > setBackgroundColor (Qt::yellow); / / Qt::green lightGray yellow ui- > tableInfo- > setItem (rowNo,MainWindow::colPartyM,item) / / set Item / / score str.setNum (score) for cells; item=new QTableWidgetItem (str,MainWindow::ctScore); / / create a new Item, set cell type to custom MainWindow::ctPartyM item- > setTextAlignment (Qt::AlignHCenter | Qt::AlignVCenter); / / text alignment format ui- > tableInfo- > setItem (rowNo,MainWindow::colScore,item); / / set Item} for cells

Each row of the table has five columns. Create a variable item of type QTableWidgetItem for each cell and set it accordingly.

The prototype of the constructor used by QTableWidgetItem is:

QTableWidgetItem::QTableWidgetItem (const QString & text, int type = Type)

Where the first parameter is the display text of the cell and the second parameter is the type of the node.

For example, the statement when creating a name cell object is:

CellItem=new QtableWidgetItem (Name,MainWindow::ctName)

Where MainWindow::ctName is a constant value of the defined enumerated type CellType.

The name cell also calls the setData () function to set up a custom data that stores the student ID.

CellItem- > setData (Qt::UserRole,QVariant (StudID))

This custom data is not displayed on the interface, but is associated with the cell.

QTableWidgetItem has some functions that set properties on cells, as follows:

SetTextAlignment (int alignment): sets the text alignment.

SetBackground (const QBrush & brush): sets the background color of the cell.

SetForeground (const QBrush & brush): sets the cell foreground color.

SetIcon (const QIcon & icon): sets a visible icon for the cell.

SetFont (const QFont & font): sets the font for cell display text.

SetCheckState (Qt::CheckState state): sets the check state of the cell and a QCheckBox component appears in the cell.

SetFlags (Qt::ItemFlags flags): sets some attribute tags for the cell.

After setting the various properties of item, use the setItem function of QTableWidget to set item to the item of the cell, for example:

Ui- > tableInfo- > setItem (rowNo,MainWindow::colName,item)

Where MainWindow::colName is a constant value of the defined enumerated type FieldColNum.

After initializing the settings, you can get the contents of the runtime table shown in figure 2. The student number is not shown in the table, which is the associated data of the "name" cell.

Get the current cell data

When the mouse clicks a cell on a table, the selected cell is the current cell. You can get the column number and row number of the current cell through currentColumn () and currentRow () of QTableWidget.

When the current cell is switched, a currentCellChanged () signal and a currentItemChanged () signal are emitted, both of which can be used, but with different parameters.

Write a slot function for the currentCellChanged () signal to get the data of the current cell and the student number information of the current line. The code is as follows:

Void MainWindow::on_tableInfo_currentCellChanged (int currentRow, int currentColumn, int previousRow, int previousColumn) {/ / response to changes in the current selected cell Q_UNUSED (previousRow); Q_UNUSED (previousColumn); QTableWidgetItem* item=ui- > tableInfo- > item (currentRow,currentColumn); / / get Item if (item==NULL) return; labCellIndex- > setText (QString::asprintf ("current cell coordinates:% d rows,% d columns, currentRow,currentColumn)) of the cell) Int cellType=item- > type (); / / get the cell type labCellType- > setText ("current cell type:% d", cellType); item=ui- > tableInfo- > item (currentRow,MainWindow::colName); / / fetch the item int ID=item- > data (Qt::UserRole). ToInt () of the cell in the first column of the current row; / / read user-defined data labStudID- > setText ("student ID:%d", ID)) / / Student ID}

In the currentCellChanged () signal, the passed parameters currentRow and currentColumn represent the row number and column number of the current cell, through which you can get the cell's QTableWidgetltem object item.

After you get the item, you get the type parameter of the cell through the type () function, which is the type parameter passed when you create the QTableWidgetItem object for the cell.

Then get the items in the name cell of the same row, and use the data () function to extract the custom data, that is, the student ID that is stored when the cell is created.

Insert, add, delete rows

The functions used by QTableWidget to handle line operations are as follows:

InsertRow (int row): insert a row before the row number row, or add a row at the end of the table if the row is equal to or greater than the total number of rows. The insertRow () function simply inserts a blank line and does not create a QTableWidgetItem object for the cell. It needs to be created manually for the cell.

RemoveRow (int row): deletes the line with the line number row.

The following is the response code for the insert Row, add Row, and Delete current Row buttons on the interface. After the row is inserted, the createItemsARow () function is called to construct a QTableWidgetItem object for each cell of the newly created blank row:

Void MainWindow::on_btnInsertRow_clicked () {/ / insert a row / / int curRow; int curRow=ui- > tableInfo- > currentRow (); / / current line number ui- > tableInfo- > insertRow (curRow); / / insert a row, but will not automatically create an item createItemsARow for the cell (curRow, "new student", "male", QDate::fromString ("1990-1-1", "yyyy-M-d"), "Miao", true,60) / / create items} void MainWindow::on_btnAppendRow_clicked () {/ / add a row / / int curRow; int curRow=ui- > tableInfo- > rowCount (); / / current line number ui- > tableInfo- > insertRow (curRow); / / add a row of createItemsARow (curRow, "freshman", "female", QDate::fromString ("2000-1-1", "yyyy-M-d"), "Manchu", false,50) at the end of the table / / create items} void MainWindow::on_btnDelCurRow_clicked () {/ / delete the current line and its items / / int curRow; int curRow=ui- > tableInfo- > currentRow (); / / current line number ui- > tableInfo- > removeRow (curRow); / / delete the current line and its items}

Automatically adjust row height and column width

QTableWidget has several functions that automatically adjust the row height and column width of the table, as follows:

ResizeColumnsToContents (): automatically adjusts the width of all columns to fit their contents.

ResizeColumnToContents (int column): automatically adjusts the width of the column whose column number is co/www.

ResizeRowsToContents (): automatically adjusts the height of all lines to fit their contents.

ResizeRowToContents (int row): automatically adjusts the height of a line whose line number is raw.

These functions are actually functions of QTableView, the parent class of QTableWidget.

Other attribute control

Sets whether the table content is editable: the EditTriggers property of QTableWidget indicates whether it is editable and how to enter the editing state. The slot function code of the Table editable check box on the interface is:

Void MainWindow::on_chkBoxTabEditable_clicked (bool checked) {/ / set editing mode if (checked) / / double click or click after getting focus to enter editing status ui- > tableInfo- > setEditTriggers (QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked); else ui- > tableInfo- > setEditTriggers (QAbstractItemView::NoEditTriggers); / / Editing} is not allowed

Set whether the row and column headers are displayed: horizontalHeader () gets the row headers, verticalHeader () gets the column headers, and then sets its visibility.

Void MainWindow::on_chkBoxHeaderH_clicked (bool checked) {/ / whether to display the horizontal header ui- > tableInfo- > horizontalHeader ()-> setVisible (checked);} void MainWindow::on_chkBoxHeaderV_clicked (bool checked) {/ / whether to display the vertical header ui- > tableInfo- > verticalHeader ()-> setVisible (checked);}

Interval row background color: the setAltematingRowColors () function can set whether the rows of the table are displayed with an alternating background color, and if it is an alternate background color, the spaced row will use gray as the background color. The specific background color setting needs to use styleSheet, which will be described in the following chapters.

Void MainWindow::on_chkBoxRowColor_clicked (bool checked) {ui- > tableInfo- > setAlternatingRowColors (checked);}

Selection mode: the setSelectionBehavior () function sets whether the selection method is cell selection or row selection:

Void MainWindow::on_rBtnSelectItem_clicked () {/ / selection behavior: cell selection ui- > tableInfo- > setSelectionBehavior (QAbstractltemView::Selectltems);} void MainWindow::on_rBtnSelectRow_clicked () {/ / selection behavior: row selection ui- > tableInfo- > setSelectionBehavior (QAbstractltemView::SelectRows);} traverse the table to read data

The "read table contents to text" button demonstrates the method of reading out all the contents of the table data area, reading out the text of each cell, and separating the text of the cells in the same line with a space as a line of text. then use this line of text as a line of text editor, the code is as follows:

Void MainWindow::on_btnReadToEdit_clicked () {/ / extract strings from all lines of QTableWidget and display them in QPlainTextEdit: QString str; QTableWidgetItem * cellItem; ui- > textEdit- > clear (); / / text editor clears for (int item0 / rowCount (); iComb +) / / Line by line {str=QString::asprintf ("line% d:", iTun1); for (int jtableInfo-> jtableInfo-> jtableInfo ()-1) Column by column, but the last column is checktype, dealing with {cellItem=ui- > tableInfo- > item (iMaginj) separately; / / getting the item str=str+cellItem- > text () + "" of the cell; / / string concatenation} cellItem=ui- > tableInfo- > item (iQuery colPartyM) / / Last column, Party member if (cellItem- > checkState () = = Qt::Checked) / / display the words str=str+ "Party member" according to check status; else str=str+ "Mass"; ui- > textEdit- > appendPlainText (str) / / add to the edit box as a line}} about the basic operation and use of Qt QTableWidget is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report