QT common controls from getting started to embedding - menu bar and dialog box

Posted by sulen on Sat, 15 Jan 2022 05:24:47 +0100

introduction

QMainWindow is a class that provides users with main window programs, including a menu bar, multiple tool bars, multiple dock widgets, a status bar and a central widget. It is the basis of many applications, such as text editor, picture editor, etc. (this chapter mainly introduces the menu bar and toolbar)

**

1, Menu bar

**
A main window has at most one menu bar. Located at the top of the main window, below the title bar of the main window.
Create a menu bar.

QMenuBar* menuBar = new QMenuBar(this);

Create a menu and call the member function addMenu of QMenu to add a menu

QAction* addMenu(QMenu * menu)
QMenu* addMenu(const QString & title) 
QMenu* addMenu(const QIcon & icon, const QString & title)

Create a menu item and call the member function addAction of QMenu to add the menu item

QAction* activeAction() 
QAction* addAction(const QString & text) 
QAction* addAction(const QIcon & icon, const QString & text) 
QAction* addAction(const QString & text, const QObject * receiver, const char * member, const QKeySequence & shortcut = 0) 
QAction* addAction(const QIcon & icon, const QString & text, const QObject * receiver, const char * member,const QKeySequence & shortcut = 0)

Example demonstration: (vs2019+qt5)

//Create menu bar
    QMenuBar* menuBar = new QMenuBar(this);
//Create menu (add to menu bar with addMenu method)
    QMenu* filename = menuBar->addMenu(QStringLiteral("file(&F)"));
//Create menu item
    QAction* openfile = new QAction(QStringLiteral("Open file(&O)"));
    QAction* opendlg = new QAction(QStringLiteral("open a dialog box(&D)"));
//Add icons to menu items
    openfile->setIcon(QIcon(":/D:/image/Luffy.png"));
    opendlg->setIcon(QIcon(":/D:/image/LuffyQ.png"));
//Add menu items with addAction
    filename->addAction(opendlg);
    filename->addAction(openfile);

Note: using the QStringLiteral macro, the constant string str in the code can be directly constructed as a QString object at compile time, so there is no additional construction overhead at run time.

Addition of resource files

openfile->setIcon(QIcon(":/D:/image/Luffy.png"));

How to add a resource that begins with "/ Luffy": / image "for a file with a relative code of" / Luffy ": / image"?
Add - > New Item - > QT - > QT resource file.

**In resource1 Add required resources (such as pictures) to QRC

Finally, write the resource with * * colon + prefix + name (relative path) * *.

**

2, Toolbar

**
There can be multiple toolbars on the toolbar of the main window. Usually, one menu corresponds to one toolbar. Toolbars can also be divided as needed.
Add header file

  • Directly call the addToolBar() function of QMainWindow class to obtain the toolbar object of the main window. This function needs to be called every time a toolbar is added
    Insert an action that belongs to the toolbar, that is, add an action on the toolbar. Add through the addAction function of QToolBar class
    The toolbar is a movable window whose docking area is determined by the allowAreas of QToolBar, including:
    1.Qt::LeftToolBarArea docked on the left
    2.Qt::RightToolBarArea is docked on the right
    3.Qt::TopToolBarArea docked at the top
    4.Qt::BottomToolBarArea docked at the bottom
    5.Qt::AllToolBarAreas can be docked at the above four locations

Use the setAllowedAreas() function to specify the docking area:

setAllowedAreas(Qt::LeftToolBarArea | Qt::RightToolBarArea)

Use the setMoveable() function to set the mobility of the toolbar:

setMoveable(false)//The toolbar cannot be moved and can only be docked at the initialized position

**

3, Dialog QDialog

**
Dialog box is an indispensable part of GUI program. Many functional components that cannot or are not suitable for being placed in the main window must be set in the dialog box. The dialog box is usually a top-level window, which appears at the top of the program to realize short-term tasks or concise user interaction.
Qt uses the QDialog class to implement the dialog box. Like the main window, we usually design a class to inherit QDialog. QDialog (and its subclasses, as well as all classes of Qt::Dialog type) has an additional explanation for its parent pointer: if the parent is NULL, the dialog box will be used as a top
Layer window, otherwise it will be the child dialog box of its parent component (at this time, its default location is the center of the parent).
The difference between the top-level window and the non top-level window is that the top-level window will have its own location in the taskbar, while the non top-level window will share the location of its parent component.
Qt's built-in dialog boxes are roughly divided into the following categories:
QColorDialog: select color
QFileDialog: select a file or directory
QFontDialog: select font
QInputDialog: allows the user to enter a value and return its value
QMessageBox: modal dialog box, used to display information, ask questions, messages, warnings and errors.
QPageSetupDialog: provides paper related options for the printer
QPrintDialog: printer configuration
QPrintPreviewDialog: Print Preview
Qpprogressdialog: displays the operation process
one ️⃣ The dialog box is divided into modal dialog box and non modal dialog box.
Modal dialog box is to block the input of other windows in the same application. Modal dialog boxes are common, such as the "open file" function. You can try to open a file in Notepad. When the open file dialog box appears, we can't operate on windows other than this dialog box.
On the contrary, the modeless dialog box, such as the Find dialog box, can continue to edit the contents of Notepad while displaying the Find dialog box.
Modal and non modal realization:
Use QDialog::exec() to implement application level modal dialog boxes
When the dialog box of this mode appears, the user must first interact with the dialog box until the dialog box is closed, and then can access other windows in the program.
Use QDialog::open() to implement the modal dialog box at the window level
This mode blocks only the window associated with the dialog box, but still allows the user to interact with other windows in the program. Window level mode is especially suitable for multi window mode.
Use QDialog::show() to implement the modeless dialog box
Modal dialog example:

We call exec() to display the dialog box, so this is a modal dialog box. When the dialog box appears, we cannot interact with the main window until we close the dialog box.

QDialog dlg1(this);
dlg1.resize(300,200);
dlg1.setWindowTitle(QStringLiteral("modal dialog box"));
dlg1.exec();

Examples of modeless dialog boxes:

Let's try to change exec() to show() to see the modeless dialog box:

QDialog dlg1(this);
dlg1.resize(300,200);
dlg1.setWindowTitle(QStringLiteral("modal dialog box"));
dlg1.show();

Did it backfire? The dialog box flashed by! This is because the show () function will not block the current thread, the dialog box will be displayed, and then the function will return immediately and the code will continue to execute. Note that the dialog is built on the stack. The show() function returns and the function ends. The dialog is destructed beyond the scope, so the dialog disappears. Once we know the reason, we can change the dialog to create an object on the heap (that is, new object). Of course, there is no such problem.
*QDialog dlg2 = new QDialog();
dlg2->resize(200, 200);
dlg2->setAttribute(Qt::WA_DeleteOnClose);// Clean up memory on shutdown
dlg2->show();
Note: the dot (.) cannot be used on the heap Yes, use - >. Moreover, because new is used to allocate space on the heap, there is no delete. Therefore, we use the setAttribute() function to automatically destroy the dialog box when it is closed.

two ️⃣ Message dialog box (QMessageBox)

QMessageBox: modal dialog box, used to display information, ask questions, etc; We generally use several static member functions provided by this class: (static member functions can be accessed in two ways: 1. Create an object; 2. Call directly through the class name)

Displays the about dialog box

void about(QWidget * parent, const QString & title, const QString & text)

This is the simplest dialog box. Its title is title, the content is text, and the parent window is parent. The dialog box has only one OK button.

Displays the error dialog box

StandardButton critical(QWidget * parent, const QString & title, const QString & text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)

The dialog box will display a red error symbol. We can indicate the buttons displayed by the buttons parameter. By default, there is only one Ok button. We can use the StandardButtons type to specify multiple buttons. The instructions are as follows:

Example:

QMessageBox::critical(this, QStringLiteral("error"), QStringLiteral("error"),QMessageBox::No);

The first parameter is the parent class, the second is the title, the third is the content, the fourth is the button name (the type is StandardButtons, and there can be two choices), and the fifth parameter is the default (the button type is StandardButtons).

Display information dialog box

StandardButton information(QWidget * parent, const QString & title, const QString & text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)

Example:

QMessageBox::information(this, QStringLiteral("information"), "infor", QMessageBox::Ok);

Displays the problem dialog box

StandardButton question(QWidget * parent, const QString & title,const QString & text, StandardButtons buttons = StandardButtons( Yes | No ), StandardButton defaultButton = NoButton)

Example:

//Get click information
if (QMessageBox::Yes== QMessageBox::question(this, QStringLiteral("problem"), "question", QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
        {
            qDebug() << "click yes";
        } 
        else
        {
            qDebug() << "click no";

        }

three ️⃣ Standard file dialog box

QFileDialog, that is, the file dialog.
We use QFileDialog::getOpenFileName() to get the path of the file to be opened. The prototype of this function is as follows:

QString getOpenFileName(QWidget * parent = 0,                //parent window
                        const QString & caption = QString(), //Dialog Title 
                        const QString & dir = QString(),     //Default path for dialog box opening
                        const QString & filter = QString(),  //Filters (for example, we use "imagefile (*. jpg*.png)" only display jpg and png files. Multiple filters use ";;" division.
                        QString * selectedFilter = 0,        //Filter selected by default
                        Options options = 0                  //Parameter setting of dialog box
                       )

The return value of QFileDialog::getOpenFileName() is the selected file path. We assign it to path. By judging whether the path is empty, you can determine whether the user has selected a file. Only when the user selects a file, do we perform the following operations.
The following are the main codes of openFile() and saveFile():

//Open file 
void MainWindow::openFile()
{ 
QString path = QFileDialog::getOpenFileName(this, tr("Open File"), ".", tr("Text Files(*.txt)")); 
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."));
 } 
}
//Save file 
void MainWindow::saveFile() 
{ 
QString path = QFileDialog::getSaveFileName(this, tr("Open 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 open 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.")); 
 }
}

four ️⃣ Other dialog boxes

Color dialog

 QColor color=    QColorDialog::getColor(QColor(255, 0, 0));//Set the default color: red. Use color to receive the selected color

Font dialog box

 bool flag;
 QFont font = QFontDialog::getFont(&flag, QFont("Hua Wen Caiyun", 36));

Demo example

Open the above dialog box in the menu bar and formulate the interface.

#include "aaa.h"
#include"qmenubar.h"
#include"qdialog.h"
#include"qfiledialog.h"
#include"qtoolbar.h"
#include"qmessagebox.h"
#include"qdebug.h"
#include"qcolordialog.h"
#include"qfontdialog.h"

aaa::aaa(QWidget *parent)
    : QWidget(parent)
{

    //Menu file
    // Using the QStringLiteral macro, the constant string str in the code can be directly constructed as a QString object at compile time, so there is no additional construction overhead at run time.
    QMenuBar* menuBar = new QMenuBar(this);
    QMenu* filename = menuBar->addMenu(QStringLiteral("file(&F)"));
    QAction* openfile = new QAction(QStringLiteral("Open file(&O)"));
    QAction* opendlg = new QAction(QStringLiteral("open a dialog box(&D)"));
    QAction* openmessage = new QAction(QStringLiteral("Opens the message dialog box(&D)"));
    QAction* opencolor = new QAction(QStringLiteral("Opens the color dialog box(&D)"));
    QAction* openfont = new QAction(QStringLiteral("Opens the font dialog box(&D)"));

    //Settings Icon
    opencolor->setIcon(QIcon(":/D:/image/sunny.png"));
    openfile->setIcon(QIcon(":/D:/image/Luffy.png"));
    opendlg->setIcon(QIcon(":/D:/image/LuffyQ.png"));
    openmessage->setIcon(QIcon(":/D:/image/up.png"));
    openfont->setIcon(QIcon(":/D:/image/sunny.png"));

    //Add to main menu
    filename->addAction(openmessage);
    filename->addAction(opendlg);
    filename->addAction(openfile);
    filename->addAction(opencolor);
    filename->addAction(openfont);

    //open a dialog box
    connect(opendlg, &QAction::triggered, [=]() {
        //Modal dialog box (cannot operate on other dialog boxes)
        QDialog dlg1(this);
        dlg1.resize(300,200);
        dlg1.setWindowTitle(QStringLiteral("modal dialog box"));
        dlg1.exec();
        //Modeless dialog box (you can operate on other dialog boxes)
       // QDialog *dlg2 = new QDialog();
        //dlg2->resize(200, 200);
        //dlg2->setAttribute(Qt::WA_DeleteOnClose);// Clean up memory on shutdown
        //dlg2->show();
        });

    //Open file
    connect(openfile, &QAction::triggered, [=]() {
        QFileDialog fdlg(this);
        fdlg.getOpenFileName(this, QStringLiteral("Select file"), "D:\\", tr("Image(*.jpg*.png)")); 
        });

    //Opens the message dialog box
    connect(openmessage, &QAction::triggered, [=]() {
        if (QMessageBox::Yes== QMessageBox::question(this, QStringLiteral("problem"), "question", QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
        {
            qDebug() << "click yes";
        } 
        else
        {
            qDebug() << "click no";

        }
        });
    //Opens the color dialog box
    connect(opencolor, &QAction::triggered, [=]() {
        QColor color=    QColorDialog::getColor(QColor(255, 0, 0));//Set the default color: red. Use color to receive the selected color
        });

    //Opens the font dialog box
    connect(openfont, &QAction::triggered, [=]() {
        bool flag;
        QFont font = QFontDialog::getFont(&flag, QFont("Hua Wen Caiyun", 36));
        qDebug() << QStringLiteral("typeface") << font.family() << QStringLiteral("Font size") << font.pointSize();
        });
    ui.setupUi(this);
}

Topics: C++ OpenCV Qt UI