繁体   English   中英

循环中的 QMessageBox 和 QFileDialog

[英]QMessageBox and QFileDialog in a loop

如果设置了项目路径,我有一个程序需要在启动时检查。 为此,我对QMessageBox进行了子类化,添加了一些自定义内容(例如使对话框更宽的间隔器),并且我正在调用QFileDialog::getExistingDirectory来获取目录。

问题是,用户可以在QFileDialog单击 Cancel 。 但我希望用户返回到QMessageBox有另一个机会设置路径或完全退出程序。 为了实现这一点,我编写了方法loop()

CustomMessageBox::loop()
{
    while (true) {
        this->exec();

        if (this->clickedButton() == setPathButton) {
            path = QFileDialog::getExistingDirectory(...);
            if (!path.isEmpty()) { break; }
        } else if (this->clickedButton() == quitButton) {
            break;
        }
    }
}

然后,我有一个方法getPath()

CustomMessageBox::getPath()
{
    loop();
    return path;
}

我在main.cpp调用它:

CustomMessageBox box;
QString path = box.getPath();

if (!path.isEmpty()) {
    // save path, bla, bla
} else {
    exit(EXIT_FAILURE)
}

这有效,但这是一个好习惯吗? 我特别询问这个while里面驻留方法exec()

您决定的 IMO 缺点:

  1. 对话框类的非标准用法。 将奇怪的循环放在某个 GUI 方法中并在其中调用标准的exec()方法,此时该方法可以很容易地以标准方式调用。
  2. 隐藏来自“用户”(另一个程序员)的exec()调用
  3. 一个getPath()方法的双重甚至三重目的:
    • 显示对话框
    • 标志对话被接受/拒绝通过空 - 非空字符串
    • 返回目录路径字符串

我建议继承QDialog (为什么是消息框?):

在 Degister 中,我采用了标准的 Push Button setPathButton和 Dialog Button Box buttonBox 然后我从框中删除了“确定”按钮:

在此处输入图片说明

#include <QtWidgets/QDialog>
#include "ui_CustomDialog.h"

class CustomDialog : public QDialog
{
    Q_OBJECT

public:
    CustomDialog(QWidget *parent = nullptr);

    QString path() const { return m_path; };

private slots:
    void on_setPathButton_clicked();
    void on_buttonBox_rejected(); // You can use any pushButton instead: on_closeButton_clicked()

private:
    Ui::CustomDialogClass ui;
    QString m_path;
};

...

#include "CustomDialog.h"    
#include <QFileDialog>

CustomDialog::CustomDialog(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
}

void CustomDialog::on_setPathButton_clicked()
{
    m_path.clear();
    QString dir = QFileDialog::getExistingDirectory();

    if (!dir.isEmpty())
    {
        m_path = dir;
        done(QDialog::Accepted);
    }
}

// You can use any pushButton instead: void on_closeButton_clicked()
void CustomDialog::on_buttonBox_rejected()
{
    reject();
}

主程序

#include "CustomDialog.h"
#include <QtWidgets/QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    CustomDialog box;    
    int code = box.exec();

    if (code == QDialog::Accepted)
    {
        qDebug() << box.path(); 
        // save path, bla, bla
    }
    else
    {
        exit(EXIT_FAILURE);
    }

    return a.exec();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM