MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); /* * tr() function, used for QT internationalization, extracting strings for internationalization * Briefly avoiding garbled characters */ setWindowTitle(tr("Main Window"));
openAction = newQAction(QIcon(":images/doc-open"),tr("&Open..."),this);//tr("&Open") there is an & before the text value, meaning this will be a shortcut key Path representation ":images" starts retrieval from images of this project openAction->setShortcuts(QKeySequence::Open); openAction->setStatusTip(tr("Open and existing file")); connect(openAction,&QAction::triggered,this,&MainWindow::open);//Concatenate three actions
In the example above, our toolbar has no picture display, basically integrated with the background. The reason is that we did not configure the resource file, so the program cannot find the image for reference. This step is like adding pictures in project properties in c#, establishing connection between pictures and program. Steps:
File -> New -> AT -> QT Resources File
We click Add Prefix below to add path name, which is the prefix below
Click Add Files to add picture files. Currently supports .png. Other formats need to be implemented by installing plugins. After adding, you can give the picture an alias. Because there is a reference relationship between the project and the picture, if an alias is defined, we can still reference the picture correctly if the project name is modified later. The language at the bottom is an option for adapting to internationalization. Filling in language will create a corresponding language folder, and system will automatically switch to corresponding path after recognition
Afterwards we modify the path in original file to :/images/doc-test
Layout Manager
Implement data linkage between a slider and spinbox
Designed knowledge points mainly function pointers. Was not very familiar with this knowledge point when just starting learning c++. Function pointer points to a specific type. Function type is determined by its parameters and return type, unrelated to function name, ex:
1 2 3
intadd(int left,int right);//Define function int(*pf)(int,int);//Uninitialized pf = add;//Assign function pointer to specific function by assignment
Parentheses around (*pf) need to be added otherwise it becomes a function returning int * integer
Layout manager is similar to Grid, StackPanel controls in WPF and winForm Code:
The main function is QDialog. By creating function and creating corresponding controls in the function, corresponding effects can be achieved. If you have touched WPF or Winform before, this part should be well understood.
Blogger mentioned modal dialog box and non-modal dialog box in this topic. In QT, modal dialog box is implemented by
1
dialog.exec();
Non-modal is implemented by show() just like in C#. But this will cause a problem. In C#, showDialog() function can be used to keep the window displayed, but in QT, it needs to place QDialog on the heap to run.
This is because show() function will not block current thread, the dialog box will verify, then function returns immediately, code continues to execute. Note, dialog is established on stack, show() function returns, MainWindow::open() function ends, dialog out of scope is destructed, so dialog box disappears. Knowing the reason, it is easy to change. We change dialog to be established on heap, naturally there is no this problem:
If you need to specify parent window, just pass in parent window during initialization. When parent window is NULL, the window will be regarded as a top-level window. Modal with parent window
If people familiar with C# may quickly link this function with what we often use
Microsoft.VisualBasic.Interaction
Link together, just definition in C# is much easier than QT, but their effects are similar.
Below is the code part in QT:
1 2 3 4 5 6 7 8
voidMainWindow::open(){ //QMessageBox::information(this,tr("Information"),tr("Open")); if(QMessageBox::Yes == QMessageBox::question(this,tr("Question"),tr("Are you OK?"),QMessageBox::Yes|QMessageBox::No|QMessageBox::Save,QMessageBox::Yes)){ QMessageBox::information(this,tr("Hmmm..."),tr("I'm glab to hear that!")); }else{ QMessageBox::information(this,tr("Hmmm..."),tr("I'm sorry!")); } }
Add File Dialog Box
After watching blog for a period of time, found that if having Winform or WPF foundation before, it is very easy to master knowledge learned currently. This should be the meaning of comprehension by analogy. First paste code of open and save. Defining Mode of file is similar to C# stream file mode, read write, read, write categories.
if(!path.isEmpty()){ QFile file(path); if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){ QMessageBox::warning(this,tr("Read File"),tr("Cannot open file:\n%1").arg(path)); return; } QTextStream in(&file); textEdit->setText(in.readAll()); file.close(); }else{ QMessageBox::warning(this,tr("Path"),tr("You did not select any file")); } }
voidMainWindow::saveFile(){ QString path = QFileDialog::getSaveFileName(this,tr("&Save File"),".",tr("Text Files(*.txt")); if(!path.isEmpty()){ QFile file(path); if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){ QMessageBox::warning(this,tr("Write File"),tr("Cannot save file:\n%1").arg(path)); return; } QTextStream out(&file); out<<textEdit->toPlainText(); file.close(); }else{ QMessageBox::warning(this,tr("Path"),tr("You did not select any file")); } }
Afterwards we need to create open action and save action in main window interface, and use connector to connect, then create a text editor called TextEdit in QT called TextBox in Winform or WPF. Here is a parameter SetCentralWidgrt which can place window in center position of parent window. If people just started C++ write accordingly may error, because saveFile and TextEdit pointers are not defined in header file. Need to add these two parameters in header file. Regarding OPenFile function, referencing blogger’s material explanation
In openFile() function, we use QFileDialog::getOpenFileName() to get path of file to be opened. This function has a long signature:
But note, all its arguments are optional, therefore to some extent, this function is also simple. These six parameters are respectively:
parent: Parent window. We introduced before, Qt’s standard dialog box provides static functions, used to return a modal dialog box (to some extent this is a manifestation of facade pattern); caption: Dialog box title; dir: Default directory when dialog opens. “.” represents program running directory, “/“ represents root directory of current drive (specifically Windows platform; Linux platform naturally refers to root directory), this parameter can also be platform related, e.g. “C:\“ etc.; filter: Filter. We use file dialog box to browse many types of files, however, many times we only hope to open specific types of files. For example, text editor hopes to open text files, image viewer hopes to open image files. Filter is used to filter specific suffixes. If we use “Image Files(.jpg .png)”, then only files with suffix jpg or png are displayed. If multiple filters are needed, use “;;” to separate, e.g. “JPEG Files(.jpg);;PNG Files(.png)”; selectedFilter: Default selected filter; options: Some parameter settings of dialog box, e.g. show folders only etc., its value is enum QFileDialog::Option, each option can be combined using | operation.
//MainWinodw.cpp MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); /* * tr() function, used for QT internationalization, extracting strings for internationalization * Briefly avoiding garbled characters */ setWindowTitle(tr("Main Window"));
openAction = newQAction(QIcon(":images/doc-test"),tr("&Open..."),this);//tr("&Open") there is an & before the text value, meaning this will be a shortcut key openAction->setShortcuts(QKeySequence::Open); openAction->setStatusTip(tr("Open and existing file")); //connect(openAction,&QAction::triggered,this,&MainWindow::open);//Concatenate three actions
saveAction = newQAction(QIcon(":images/doc-test"),tr("&Save..."),this); saveAction->setShortcuts(QKeySequence::Save); saveAction->setStatusTip(tr("Save as a new file"));
// QObject::connect(&newspaper,&Newspaper::newPaper,&reader,&Reader::receriveNewpaper); // newspaper.send(); /* * Control display of controls in MainWinodow.cpp */ QApplication app(argc,argv);
// QObject::connect(&newspaper,&Newspaper::newPaper,&reader,&Reader::receriveNewpaper); // newspaper.send(); /* * Control display of controls in MainWinodow.cpp */