In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains how to use the Qt StandardItemModel data model in CAccord Category +. The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the Qt StandardItemModel data model.
QStandardItemModel is a standard data management method based on Model/View V model based on item data. Model/View is a data orchestration structure in Qt, in which Model represents the model, View represents the view, the view is the interface component for displaying and editing data, and the model is the interface between the view and the original data. Usually, this kind of structure is often used in the database, for example, the model structure is responsible for reading or writing to the database. The view structure is responsible for displaying data, which is well organized and easy to write code for maintenance.
The QStandardItemModel component is usually used with the TableView component and is automatically synchronized to the component when the record in the database or text changes. The UI interface is drawn first.
Secondly, bind the top ToolBar menu and add the description of the corresponding functional attributes to the menu.
Initialization constructor: when the program runs, we need to initialize the controls on the page one by one, and bind the Table table to the model by calling ui- > tableView- > setModel (model).
# include "mainwindow.h" # include "ui_mainwindow.h" # include # include / / default constructor / / https://www.cnblogs.com/lysharkMainWindow::MainWindow(QWidget * parent): QMainWindow (parent), ui (new Ui::MainWindow) {ui- > setupUi (this); / / initialization part model = new QStandardItemModel (3pencil FixedColumnCountthis); / / data model initialization selection = new QItemSelectionModel (model) / / Item Select model / / set data model ui- > tableView- > setModel (model) for TableView; / / set data model ui- > tableView- > setSelectionModel (selection); / / set selection model / / disable all Action options by default, leaving only ui- > actionSave- > setEnabled (false); ui- > actionView- > setEnabled (false); ui- > actionAppend- > setEnabled (false) Ui- > actionDelete- > setEnabled (false); ui- > actionInsert- > setEnabled (false); / / create a status bar component to display the cell location LabCurFile = new QLabel ("current file:", this); LabCurFile- > setMinimumWidth (200); LabCellPos = new QLabel ("current cell:", this); LabCellPos- > setMinimumWidth (Qt::AlignHCenter); LabCellText = new QLabel ("cell content:", this) LabCellText- > setMinimumWidth; ui- > statusbar- > addWidget (LabCurFile); ui- > statusbar- > addWidget (LabCellPos); ui- > statusbar- > addWidget (LabCellText); / / Select the signal and slot connect (selection,SIGNAL (currentChanged (QModelIndex,QModelIndex)), this,SLOT (on_currentChanged (QModelIndex,QModelIndex));} MainWindow::~MainWindow () {delete ui;}
Initialization also needs to bind an on_currentChanged (QModelIndex,QModelIndex) signal, when the user selects the specified cell, the corresponding user.
/ / Select the response when the cell changes, and trigger / / https://www.cnblogs.com/lysharkvoid MainWindow::on_currentChanged (const QModelIndex & current, const QModelIndex & previous) {Q_UNUSED (previous) by binding the signal and slot function in the constructor. If (current.isValid ()) / / the current model index is valid {LabCellPos- > setText ("current cell:% d rows,% d columns", current.row (), current.column ()); / / displays the row and column numbers of the model index QStandardItem * aItem; aItem=model- > itemFromIndex (current) / / get Item this- > LabCellText- > setText from the model index ("Cell content:" + aItem- > text ()); / / display the text content of the item}}
When the page is initialized, the default interface is as follows:
Open and fill components: when the toolbar to open the file is triggered when clicked, open the file through the aFile.open, read the file loop, and the contents of the file line by line appended to the QStringList fFileContent, when the append is finished, directly call iniModelFromStringList (fFileContent); complete the initialization of the page TableView component, and set the other control state to clickable.
Void MainWindow::on_actionOpen_triggered () {QString curPath=QCoreApplication::applicationDirPath (); / get the path of the application / / call the Open File dialog box to open a file / / https://www.cnblogs.com/lyshark QString aFileName=QFileDialog::getOpenFileName (this, "Open a file", curPath, "data file (* .txt);; all files (*. *)") If (aFileName.isEmpty ()) {return; / / exit} QStringList fFileContent; / / File content string list QFile aFile (aFileName) if no file is selected / / read if as a file (aFile.open (QIODevice::ReadOnly | QIODevice::Text)) / / Open the file {QTextStream aStream (& aFile) as read-only text; / / read the file ui- > plainTextEdit- > clear () with a text stream / / clear the list / / Loop read as long as it is not empty while (! aStream.atEnd ()) {QString str=aStream.readLine (); / / read the file's line ui- > plainTextEdit- > appendPlainText (str); / / add to the text box to display fFileContent.append (str) / / add to StringList} aFile.close (); / / close the file iniModelFromStringList (fFileContent); / / initialize the data model from the contents of StringList} / / after opening the file, you can open all Action: ui- > actionSave- > setEnabled (true); ui- > actionView- > setEnabled (true). Ui- > actionAppend- > setEnabled (true); ui- > actionDelete- > setEnabled (true); ui- > actionInsert- > setEnabled (true); / / after opening the file successfully, set the current file column this- > LabCurFile- > setText ("current file:" + aFileName); / / status bar display}
As shown in the above iniModelFromStringList (fFileContent); the function is added later, and we need to implement it ourselves. The function is to obtain data from the incoming StringList and initialize the data into the TableView model. The implementation code is as follows.
Void MainWindow::iniModelFromStringList (QStringList& aFileContent) {int rowCnt=aFileContent.count (); / / number of lines of text, the first line is the title model- > setRowCount (rowCnt-1); / / the actual number of rows of data, to subtract 1 / / set header QString header=aFileContent.at (0) from the header / / the first line is the header / / one or more spaces, a string separated by TAB and other delimiters, decomposed into a StringList / / https://www.cnblogs.com/lyshark QStringList headerList=header.split (QRegExp ("\\ s +"), QString::SkipEmptyParts); model- > setHorizontalHeaderLabels (headerList); / / set header text / / set the data in the table int x = 0line y = 0; QStandardItem * Item / / cycle as many columns of data as there are / / https://www.cnblogs.com/lyshark for
< rowCnt; x++) { QString LineText = aFileContent.at(x); // 获取数据区的一行 // 一个或多个空格、TAB等分隔符隔开的字符串、分解为一个StringList QStringList tmpList=LineText.split(QRegExp("\\s+"),QString::SkipEmptyParts); // 循环列数,也就是循环FixedColumnCount,其中tmpList中的内容也是. for(y=0; y < FixedColumnCount-1; y++) { Item = new QStandardItem(tmpList.at(y)); // 创建item model->SetItem (xmelet 1); / / set Item} / / the last data for a row and column position of the model needs to be judged, and the status Item=new QStandardItem (headerList.at (y)) is set separately; / / the last column is Checkable, which needs to set Item- > setCheckable (true) / / set to Checkable / / to determine whether the last value is 0 if (tmpList.at (y) = = "0") Item- > setCheckState (Qt::Unchecked); / / set the check status else Item- > setCheckState (Qt::Checked) according to the data; model- > setItem (xmem1memy item) / / set Item}} for a column position in the model
The effect after initializing the component is as follows:
Implement to add a row of data: add a row of data to the TableView and insert it at the end of the file.
Void MainWindow::on_actionAppend_triggered () {QList ItemList; / / create a temporary container QStandardItem * Item; / / simulate adding a column of data for (int xchang0; xcolumnCount ()-1). ToString (); Item=new QStandardItem (str); / / create a "qualified" field Item- > setCheckable (true) / / set the status to true ItemList insertRow (model- > rowCount (), ItemList); / / insert a row that requires Item QModelIndex curIndex=model- > index for each Cell (model- > rowCount ()-1); / / create ModelIndex selection- > clearSelection () for the last line; / / clear the current selection selection- > setCurrentIndex (curIndex,QItemSelectionModel::Select) / / sets the currently selected item to be the currently selected row}
Insert code to demonstrate the effect:
Implement insert a row of data: insert a row of data for TableView (insert data anywhere in the file)
/ / https://www.cnblogs.com/lysharkvoid MainWindow::on_actionInsert_triggered () {QList ItemList; / / QStandardItem's list class QStandardItem * Item; / / simulates the insertion of the first five columns of data for (int item0position icolumnCount ()-1). ToString (); Item=new QStandardItem (str); / / create Item Item- > setCheckable (true) / / set to use CheckBox ItemListinsertRow (curIndex.row (), ItemList); / / insert a line selection- > clearSelection () in front of the current row; / / clear the current selection selection- > setCurrentIndex (curIndex,QItemSelectionModel::Select); / / set the current selection to the currently selected line}
Insert code to demonstrate the effect:
To delete a row of data: before deleting the data, you need to determine the currently selected row by selection- > currentIndex (), and remove it by model- > removeRow ().
/ / https://www.cnblogs.com/lysharkvoid MainWindow::on_actionDelete_triggered () {QModelIndex curIndex = selection- > currentIndex (); / / get the model index of the currently selected cell / / first determine whether it is the last line if (curIndex.row () = = model- > rowCount ()-1) {model- > removeRow (curIndex.row ()) / / delete the last line} else {model- > removeRow (curIndex.row ()); / / Delete a line and reset the currently selected line selection- > setCurrentIndex (curIndex,QItemSelectionModel::Select);}}
Delete code effect demo:
Achieve font data alignment: fonts in the table can be aligned in a variety of ways, which can be divided into center alignment, left alignment and right alignment.
/ / set table center alignment void MainWindow::on_pushButton_clicked () {if (! selection- > hasSelection ()) return; QModelIndexList selectedIndex=selection- > selectedIndexes (); QModelIndex Index; QStandardItem * Item; for (int iTuno; iitemFromIndex (Index); Item- > setTextAlignment (Qt::AlignHCenter)) }} / / set table left alignment / / https://www.cnblogs.com/lysharkvoid MainWindow::on_pushButton_2_clicked () {if (! selection- > hasSelection ()) / / the unselected item return;// gets the model index list of the selected cells, which can be multi-selected QModelIndexList selectedIndex=selection- > selectedIndexes (); for (int itemFromIndex (aIndex) / / get a cell item data object aItem- > setTextAlignment (Qt::AlignLeft); / / set text alignment}} / / set table right alignment void MainWindow::on_pushButton_3_clicked () {if (! selection- > hasSelection ()) return; QModelIndexList selectedIndex=selection- > selectedIndexes (); QModelIndex aIndex; QStandardItem * aItem; for (int itemFromIndex (aIndex); aItem- > setTextAlignment (Qt::AlignRight) }}
Demonstrate the effect of aligning code:
Bold font data: bold the font of the selected line.
/ / set font bold display / / https://www.cnblogs.com/lysharkvoid MainWindow::on_pushButton_4_clicked () {if (! selection- > hasSelection ()) return;// get the model index list of selected cells QModelIndexList selectedIndex=selection- > selectedIndexes (); for (int itemFromIndex (aIndex); / / get item data QFont font=aItem- > font (); / / get font font.setBold (true) / / set whether the font is bold aItem- > setFont (font); / / reset the font}
Bold code effect demonstration:
To save the file: triggered when the save file is clicked, by facilitating the data in the TableWidget model component and passing the data through aStream clear (); / / getting the header text for (xSecret0; xcolumnCount (); xsave +) {Item=model- > horizontalHeaderItem (x); / / getting the item data of the header str= str + Item- > text () + "\ t\ t" / / separate} aStream appendPlainText (str) with TAB tabs; / / get the datazone text for (xroom0; x
< model->RowCount (); x str +) {str = ""; for (yellow0; y)
< model->ColumnCount ()-1; yearly +) {Item=model- > item (XMagy); str=str + Item- > text () + QString::asprintf ("\ t\ t");} / / A pair of last columns need to be converted. If it is judged to be selected, write 1 otherwise write 0 Item=model- > item (xMagy) If (Item- > checkState () = = Qt::Checked) str= str + "1"; else str= str + "0"; ui- > plainTextEdit- > appendPlainText (str); aStream clear (); QStandardItem * Item; QString str; / / get the header words int xonomo; xcolumnCount () Xregions +) {/ / Item=model- > horizontalHeaderItem (x); str= str + Item- > text () + "\ t";} ui- > plainTextEdit- > appendPlainText (str); / / get each row for of the datazone (xroom0; xrowCount (); xroom+) {str= "; for (ypend0; ycolumnCount ()-1 If +) {Item=model- > item (XMagney); str= str + Item- > text () + QString::asprintf ("\ t");} Item=model- > item (xQuery); if (Item- > checkState () = = Qt::Checked) str= str + "1"; else str= str + "0" Ui- > plainTextEdit- > appendPlainText (str);}}
After saving the file, it is as follows:
Thank you for your reading, the above is the content of "how to use the Qt StandardItemModel data model in CCMG +". After the study of this article, I believe you have a more profound understanding of how to use the Qt StandardItemModel data model in Cpicket +, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.