C++ Qt development: standard Dialog dialog component

Qt is a cross-platform C++ graphical interface development library. You can use Qt to quickly develop cross-platform form applications. In Qt, we can drag and drop different components into specified locations to achieve graphical implementation. Development greatly facilitates development efficiency. This chapter will focus on the common methods and flexible applications of the two dialog components QInputDialog and QFileDialog , which are standard dialog boxes.

In Qt, standard dialog boxes provide some common user interaction interfaces for performing specific tasks, such as obtaining user input, selecting file paths, displaying messages, etc. These dialog boxes typically have a standardized appearance and behavior, allowing for consistency across different platforms. In the general development process, the standard dialog box is one of the commonly used tools for developers.

1.1 QInputDialog

QInputDialogClass provides a simple method for obtaining user input. It can be used to get input of text, integer, floating point, etc. types.

The following is a description and overview of some commonly used methods of the QInputDialog class, listed in table format:

method describe
getText(QWidget *parent, const QString &title, const QString &label, QLineEdit::EchoMode mode = QLineEdit::Normal, const QString &text = QString(), bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()) -> QString Displays a text input dialog box that returns the text entered by the user.
getInt(QWidget *parent, const QString &title, const QString &label, int value = 0, int minValue = -2147483647, int maxValue = 2147483647, int step = 1, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()) -> int Displays an integer input dialog box, returning the integer entered by the user.
getDouble(QWidget *parent, const QString &title, const QString &label, double value = 0, double minValue = -2147483647, double maxValue = 2147483647, int decimals = 1, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()) -> double Displays a floating point input dialog box and returns the floating point number entered by the user.
getItem(QWidget *parent, const QString &title, const QString &label, const QStringList &items, int current = 0, bool editable = true, bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags(), Qt::InputMethodHints inputMethodHints = Qt::ImhNone) -> QString Displays a list input dialog box, returning the user-selected item.
getMultiLineText(QWidget *parent, const QString &title, const QString &label, const QString &text = QString(), bool *ok = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()) -> QString Displays a multi-line text input dialog box, returning the text entered by the user.

These methods provide different types of input dialog boxes, including text, integer, floating point number, list, etc. Through these methods, developers can easily interact with users and obtain information entered by users. It should be noted that these methods are static methods and can be called directly through the class name QInputDialog.

In order to conveniently demonstrate the use of these four standard input boxes, readers here can draw the page layout as shown belowUIand import it themselves#include <QInputDialog>Two header files with#include <QLineEdit>;

1.1.3 Text input

is implemented through the getText method, QInputDialog::getText is a static method used in Qt to display a simple dialog box containing a field for entering text method. This method is typically used to obtain text entered by the user.

The parameters of the method include:

  • parent: The parent window of the dialog box. Passing in nullptr means there is no parent window.
  • caption: The title of the dialog box.
  • label: Text label above the input field.
  • echo: The echo mode when entering text, which can be QLineEdit::Normal, QLineEdit::NoEcho, etc.
  • text: Initial text.
  • ok: A Boolean pointer used to obtain the state of the dialog box's OK button.
  • flags: Optional window flag.

The method returns the text entered by the user, or an empty string if the user canceled the dialog box. You can adjust the label, initial text, echo mode and other parameters as needed to meet your specific needs.

This method requires the user to pass in necessary parameters such as titleEchoMode. It should be noted that if the reader wants to hide the displayed text when typing, they can set it directlyQLineEdit::Password is password mode, the password entered at this time will be replaced by *, the code is as follows;

void MainWindow::on_pushButton_text_clicked()
{
    
    
    QString dlgTitle="输入文字对话框";
    QString txtLabel="请输入文件名";
    QString defaultInput="新建文件.txt";
    QLineEdit::EchoMode echoMode=QLineEdit::Normal;       // 正常文字输入
    // QLineEdit::EchoMode echoMode=QLineEdit::Password;  // 密码输入

    bool flag = false;
    QString text = QInputDialog::getText(this, dlgTitle,txtLabel, echoMode,defaultInput, &flag);
    if (flag && !text.isEmpty())
    {
    
    
        ui->plainTextEdit->appendPlainText(text);
    }
}

After running the code, click the文本输入 button, and the input box will pop up, as shown below;

1.1.2 Integer input

is implemented through the getInt method, QInputDialog::getInt is a static method in Qt used to display a simple dialog box containing a field for entering an integer method. This method is typically used to obtain an integer entered by the user.

The parameters of the method include:

  • parent: The parent window of the dialog box. Passing in nullptr means there is no parent window.
  • caption: The title of the dialog box.
  • label: Text label above the input field.
  • value: Initial value.
  • min: minimum value.
  • max: maximum value.
  • step: Step size, indicating the amount of each increase or decrease.
  • ok: A Boolean pointer used to obtain the state of the dialog box's OK button.
  • flags: Optional window flag.

The method returns the integer entered by the user, or 0 if the user canceled the dialog box. You can adjust the label, initial value, range, step size and other parameters as needed to meet your specific needs.

This method provides a SpinBox selection box, which can limit the minimum value by passing in minValue when inputting, maxValueLimit the maximum value and set each step size throughstepValue, the code is as follows;

void MainWindow::on_pushButton_int_clicked()
{
    
    
    QString dlgTitle="输入整数对话框";
    QString txtLabel="设置字体大小";
    int defaultValue=ui->plainTextEdit->font().pointSize();   // 现有字体大小
    int minValue=6, maxValue=50, stepValue=1;                 // 范围(步长)
    bool flag=false;
    int inputValue = QInputDialog::getInt(this, dlgTitle,txtLabel,defaultValue, minValue,maxValue,stepValue,&flag);
    if (flag)
    {
    
    
        QFont font=ui->plainTextEdit->font();
        font.setPointSize(inputValue);
        ui->plainTextEdit->setFont(font);

        // 显示在编辑框内
        QString stringValue = QString::number(inputValue);
        ui->plainTextEdit->appendPlainText(stringValue);
    }
}

After running the code, click the 整数输入 button, and the input box will pop up. The minimum integer selection is limited to 6 and the maximum limit is 50, as shown below;

1.1.3 Floating point input

is implemented through the getDouble method, QInputDialog::getDouble is used in Qt to display a simple dialog box that contains a field for entering floating point numbers. static methods. This method is usually used to obtain floating point numbers entered by the user.

The parameters of the method include:

  • parent: The parent window of the dialog box. Passing in nullptr means there is no parent window.
  • caption: The title of the dialog box.
  • label: Text label above the input field.
  • value: Initial value.
  • min: minimum value.
  • max: maximum value.
  • decimals: Number of decimal places.
  • ok: A Boolean pointer used to obtain the state of the dialog box's OK button.
  • flags: Optional window flag.

Method returns a floating point number entered by the user, or 0.0 if the user canceled the dialog box. You can adjust parameters such as label, initial value, range, decimal places, etc. to meet your specific needs.

This method provides a SpinBox selection box. The input length of floating point numbers can also be limited. At the same time, floating point numbers can also specify the number of decimal points. Through decimalsSpecify two-digit display, the code is as follows;

void MainWindow::on_pushButton_float_clicked()
{
    
    
    QString dlgTitle="输入浮点数对话框";
    QString txtLabel="输入一个浮点数";
    float defaultValue=3.13;

    float minValue=0, maxValue=10000;  // 范围
    int decimals=2;                    // 小数点位数

    bool flag=false;
    float inputValue = QInputDialog::getDouble(this, dlgTitle,txtLabel,defaultValue, minValue,maxValue,decimals,&flag);
    if (flag)
    {
    
    
        QString str=QString::asprintf("输入了一个浮点数:%.2f",inputValue);
        ui->plainTextEdit->appendPlainText(str);
    }
}

After running the code, click the 浮点数输入 button, and the input box will pop up. The minimum floating point number selection is limited to 0 and the maximum limit is The reserved length is two digits, as shown below;10000, the default value is3.13

1.1.4 Radio button input

is implemented through the getItem method, which is suitable for allowing the user to select only specific content. QInputDialog::getItem is used to display a simple dialog box in Qt , which contains a static method for a drop-down box (QComboBox) for users to select. This method is typically used to get the item selected by the user from a list.

The parameters of the method include:

  • parent: The parent window of the dialog box. Passing in nullptr means there is no parent window.
  • caption: The title of the dialog box.
  • label: The text label above the drop-down box.
  • items: A list of strings representing the options in the drop-down box.
  • currentItem: Index of the initially selected item.
  • editable: Whether to allow users to edit the text in the drop-down box.
  • ok: A Boolean pointer used to obtain the state of the dialog box's OK button. In this example, we pass nullptr because we don’t care about the state of the OK button.
  • flags: Optional window flag.

The method returns the item selected by the user, or an empty string if the user canceled the dialog box. You can adjust the label, initial selection, editability and other parameters as needed to meet your specific needs. The code is as follows;

void MainWindow::on_pushButton_checkbox_clicked()
{
    
    
    QStringList items;                        // 列表内容
    items <<"优秀"<<"良好"<<"合格"<<"不合格";    // 放入列表

    QString dlgTitle="条目选择对话框";
    QString txtLabel="请选择级别";
    int curIndex=0;                            // 初始选择项
    bool editable=false;                       // 是否可编辑
    bool flag=false;
    QString text = QInputDialog::getItem(this, dlgTitle,txtLabel,items,curIndex,editable,&flag);

    if (flag && !text.isEmpty())
    {
    
    
        ui->plainTextEdit->appendPlainText(text);
    }
}

Click the单选框输入 button after the code is run, and the radio button form will pop up, and the reader can select the corresponding option, as shown below;

2.1 QFileDialog

QFileDialog class Standard dialog box for opening and saving files. It provides a user-friendly interface, allowing users to easily select files or directories, and also needs to import header files when using it. #include <QFileDialog>

The following is a description and overview of some commonly used methods of the QFileDialog class, listed in table format:

method describe
getOpenFileName(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Opens a file dialog box and gets the user-selected file name.
getOpenFileNames(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Opens a file dialog box to obtain multiple file names selected by the user.
getSaveFileName(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Save file dialog box to obtain the file name entered by the user.
getExistingDirectory(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), Options options = ShowDirsOnlyDontResolveSymlinks) Used to get the path to an existing directory in the file system.
getExistingDirectoryUrl(QWidget *parent = nullptr, const QString &caption = QString(), const QUrl &dir = QUrl(), QFileDialog::Options options = ShowDirsOnlyDontResolveSymlinks) Used to get the path to an existing directory in the file system.
getSaveFileUrl(QWidget *parent = nullptr, const QString &caption = QString(), const QUrl &dir = QUrl(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Save file dialog to get the URL of the file entered by the user.
getOpenFileUrl(QWidget *parent = nullptr, const QString &caption = QString(), const QUrl &dir = QUrl(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Opens a file dialog box and gets the URL of the file selected by the user.
getOpenFileUrls(QWidget *parent = nullptr, const QString &caption = QString(), const QUrl &dir = QUrl(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Opens a file dialog box and gets the URLs of multiple files selected by the user.
getSaveFileUrls(QWidget *parent = nullptr, const QString &caption = QString(), const QUrl &dir = QUrl(), const QString &filter = QString(), QString *selectedFilter = nullptr, Options options = 0) Save file dialog to get the URLs of multiple files entered by the user.
setLabelText(QFileDialog::DialogLabel label, const QString &text) Sets the text of the specified label in the dialog box.
setLabelText(QFileDialog::DialogLabel label, const QUrl &url) Sets the text of the specified label in the dialog box to the URL.
setOption(QFileDialog::Option option, bool on = true) Enables or disables the specified option of the dialog box.
setOptions(QFileDialog::Options options) Set options for the dialog box.
setFileMode(QFileDialog::FileMode mode) Set the file mode of the dialog box (open, save, directory selection, etc.).
setAcceptMode(QFileDialog::AcceptMode mode) Set the acceptance mode of the dialog box, whether to open the file or save the file.
setViewMode(QFileDialog::ViewMode mode) Set the view mode of the dialog box, such as detailed view, icon view, etc.
setDirectory(const QString &directory) Sets the default directory when the dialog box opens.
setDirectoryUrl(const QUrl &directory) Sets the URL of the default directory when the dialog box opens.
setFilter(const QString &filter) Set the dialog box's file type filter, such as "Text Files (.txt);; All Files ()".
setNameFilter(const QString &filter) Set the file name filter of the dialog box, such as "*.txt".
setDefaultSuffix(const QString &suffix) 设置默认的文件后缀,用于在用户未指定文件后缀时追加到文件名。
setMimeTypeFilters(const QStringList &filters) 设置对话框的 MIME 类型过滤器。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。
setDefaultSuffix(const QString &suffix) 设置默认的文件后缀,用于在用户未指定文件后缀时追加到文件名。
setMimeTypeFilters(const QStringList &filters) 设置对话框的 MIME 类型过滤器。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。
setDefaultSuffix(const QString &suffix) 设置默认的文件后缀,用于在用户未指定文件后缀时追加到文件名。
setMimeTypeFilters(const QStringList &filters) 设置对话框的 MIME 类型过滤器。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。
setDefaultSuffix(const QString &suffix) 设置默认的文件后缀,用于在用户未指定文件后缀时追加到文件名。
setMimeTypeFilters(const QStringList &filters) 设置对话框的 MIME 类型过滤器。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。
setDefaultSuffix(const QString &suffix) 设置默认的文件后缀,用于在用户未指定文件后缀时追加到文件名。
setMimeTypeFilters(const QStringList &filters) 设置对话框的 MIME 类型过滤器。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。
setLabelText(QFileDialog::DialogLabel label, const QString &text) 设置对话框中指定标签的文本。
setLabelText(QFileDialog::DialogLabel label, const QUrl &url) 设置对话框中指定标签的文本为 URL。
setOption(QFileDialog::Option option, bool on = true) 启用或禁用对话框的指定选项。
setOptions(QFileDialog::Options options) 设置对话框的选项。
setFileMode(QFileDialog::FileMode mode) 设置对话框的文件模式(打开、保存、目录选择等)。
setAcceptMode(QFileDialog::AcceptMode mode) 设置对话框的接受模式,是打开文件还是保存文件。
setViewMode(QFileDialog::ViewMode mode) 设置对话框的视图模式,如详细视图、图标视图等。
setDirectory(const QString &directory) 设置对话框打开时的默认目录。
setDirectoryUrl(const QUrl &directory) 设置对话框打开时的默认目录的 URL。
setFilter(const QString &filter) 设置对话框的文件类型过滤器,如"文本文件 (.txt);;所有文件 ()"。
setNameFilter(const QString &filter) 设置对话框的文件名过滤器,如"*.txt"。
setDefaultSuffix(const QString &suffix) 设置默认的文件后缀,用于在用户未指定文件后缀时追加到文件名。
setMimeTypeFilters(const QStringList &filters) 设置对话框的 MIME 类型过滤器。
setSidebarUrls(const QList<QUrl> &urls) 设置对话框侧边栏的 URL 列表。
setProxyModel(QAbstractProxyModel *proxyModel) 设置对话框使用的代理模型。
setHistory(const QStringList &paths) 设置对话框历史记录的路径列表。

这些方法提供了一系列功能,包括打开文件、保存文件、选择目录等,以及对对话框的一些属性进行设置。这样,开发者可以方便地使用这些方法构建出符合应用需求的文件对话框。需要注意的是,这些方法中的许多参数都有默认值,因此在大多数情况下,开发者可以选择性地调用这些方法。

2.1.1 选择文件

在选择单个文件时可以通过调用getOpenFileName方法实现,QFileDialog::getOpenFileName 是 Qt 中用于显示打开文件对话框并获取用户选择的文件名的静态方法。它通常用于在用户需要选择一个文件进行打开操作时,例如加载文件等场景。

方法的参数包括:

  • parent: 对话框的父窗口。传入 nullptr 表示没有父窗口。
  • caption: 对话框的标题。
  • dir: 默认的目录路径。
  • filter: 文件类型过滤器,用于筛选可打开的文件类型。可以使用分号分隔多个过滤器,例如 "Text Files (*.txt);;All Files (*)"

方法返回用户选择的文件名,如果用户取消了对话框,则返回一个空字符串。你可以根据需要调整过滤器、默认目录等参数,以满足你的具体需求。

通过最后一个参数来指定需要打开的文件类型,通常可传入一组字符串来实现过滤,当打开后可以通过aFileName拿到文件具体路径,代码如下;

void MainWindow::on_pushButton_file_clicked()
{
    
    
    QString curPath=QDir::currentPath();                                       // 获取系统当前目录
    //  QString  curPath=QCoreApplication::applicationDirPath();               // 获取应用程序的路径
    QString dlgTitle="选择一个文件";                                             // 对话框标题
    QString filter="文本文件(*.txt);;图片文件(*.jpg *.gif *.png);;所有文件(*.*)";  // 文件过滤器

    QString aFileName=QFileDialog::getOpenFileName(this,dlgTitle,curPath,filter);

    if (!aFileName.isEmpty())
    {
    
    
        ui->plainTextEdit->appendPlainText(aFileName);
    }
}

打开效果图如下所示;

同理,当我们需要选择多个文件并打开时只需要将QString修改为QStringList这样当文件被打开后则可以通过循环输出fileList列表来获取所有路径信息,如下代码所示;

void MainWindow::on_pushButton_multiple_clicked()
{
    
    
    // QString curPath=QCoreApplication::applicationDirPath();                // 获取应用程序的路径
    QString curPath=QDir::currentPath();                                      // 获取系统当前目录
    QString dlgTitle="选择多个文件";                                            // 对话框标题
    QString filter="文本文件(*.txt);;图片文件(*.jpg *.gif *.png);;所有文件(*.*)"; // 文件过滤器

    QStringList fileList=QFileDialog::getOpenFileNames(this,dlgTitle,curPath,filter);
    for (int i=0; i<fileList.count();i++)
    {
    
    
        // 循环将文件路径添加到列表中
        ui->plainTextEdit->appendPlainText(fileList.at(i));
    }
}

在选择时可以通过拖拽选中的方式选择多个文件,如下图所示;

2.1.2 选择目录

选择目录时可以调用getExistingDirectory方法,QFileDialog::getExistingDirectory 是 Qt 中用于显示选择目录对话框并获取用户选择的目录的静态方法。它通常用于在用户需要选择一个目录时,例如保存文件到特定目录或加载文件等场景。

方法的参数包括:

  • parent: 对话框的父窗口。传入 nullptr 表示没有父窗口。
  • caption: 对话框的标题。
  • dir: 默认的目录路径。
  • options: 对话框的选项。在示例中,使用了 QFileDialog::ShowDirsOnly 表示只显示目录,并且 QFileDialog::DontResolveSymlinks 表示不解析符号链接。

方法返回用户选择的目录路径,如果用户取消了对话框,则返回一个空字符串。你可以根据需要调整默认目录、选项等参数,以满足你的具体需求。

void MainWindow::on_pushButton_dirfile_clicked()
{
    
    
    QString curPath=QCoreApplication::applicationDirPath();    // 获取应用程序的路径
    // QString curPath=QDir::currentPath();                    // 获取系统当前目录

    // 调用打开文件对话框打开一个文件
    QString dlgTitle="选择一个目录";                             // 对话框标题
    QString selectedDir=QFileDialog::getExistingDirectory(this,dlgTitle,curPath,QFileDialog::ShowDirsOnly);
    if (!selectedDir.isEmpty())
    {
    
    
        ui->plainTextEdit->appendPlainText(selectedDir);
    }
}

选择目录输出效果图如下所示;

2.1.3 保存文件

保存文件可以通过调用getSaveFileName方法来实现,QFileDialog::getSaveFileName 是 Qt 中用于显示保存文件对话框并获取用户选择的文件名的静态方法。它通常用于在用户将文件保存到磁盘时获取文件的保存路径。

该方法的参数包括:

  • parent: 对话框的父窗口。传入 nullptr 表示没有父窗口。
  • caption: 对话框的标题。
  • dir: 默认的目录路径。
  • filter: 文件类型过滤器,用于筛选可保存的文件类型。可以使用分号分隔多个过滤器,例如 "Text Files (*.txt);;All Files (*)"

方法返回用户选择的文件名,如果用户取消了对话框,则返回一个空字符串。你可以根据需要调整过滤器、默认目录等参数,以满足你的具体需求。

void MainWindow::on_pushButton_save_clicked()
{
    
    
    QString curPath=QCoreApplication::applicationDirPath();                  // 获取应用程序的路径
    QString dlgTitle="保存文件";                                              // 对话框标题
    QString filter="文本文件(*.txt);;h文件(*.h);;C++文件(.cpp);;所有文件(*.*)"; // 文件过滤器
    QString aFileName=QFileDialog::getSaveFileName(this,dlgTitle,curPath,filter);
    if (!aFileName.isEmpty())
    {
    
    
        ui->plainTextEdit->appendPlainText(aFileName);
    }
}

保存文件对话框如下图所示,当点击后则可以将文件保存到特定目录下;

Guess you like

Origin blog.csdn.net/lyshark_csdn/article/details/135041765