簡體   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