【问题标题】:Qt/C++ How can I disconnect a QProgressDialog::canceled signal to its QProgressDialog::cancel slot?Qt/C++ 如何断开 QProgressDialog::canceled 信号与其 QProgressDialog::cancel 槽的连接?
【发布时间】:2020-11-23 18:02:00
【问题描述】:

我有一个QProgressDialog,我想覆盖它的cancel() 槽来改变它的行为。

我不想关闭对话框,而是想做一些其他操作,然后在 QThread 完成后关闭对话框,然后再关闭对话框。

我尝试断开 canceled/cancel 信号/插槽对并重新连接到新行为,但它似乎没有太大变化。

只要我点击取消按钮,进度对话框就会首先关闭,然后我的 lambda 会继续执行。

Qobject::disconnect(m_progressdialog, &QProgressDialog::canceled, m_progressdialog, &QProgressDialog::cancel);

Qobject::connect(m_progressdialog, &QProgressDialog::canceled, [](){
  // continue displaying the dialog as an occupation bar
  m_progressdialog->setValue(0);
  // do some other things
  // a lot of code
  // ...
  // only later close the dialog
  m_progressdialog->close();
});

有没有办法正确地做到这一点?

【问题讨论】:

    标签: c++ c++11 qt5 qprogressdialog


    【解决方案1】:

    我不知道你的整个代码,但是according to the documentation,这个想法或多或少和你说的一样:连接信号QProgressDialog::canceled()的插槽。

    以下代码只是一个示例,但它可以正常工作。在这种情况下,不是使用自己的 Qt 属性wasCanceled,而是使用布尔值来控制何时停止和取消QProgressDialog

    dialog.h

    #ifndef DIALOG_H
    #define DIALOG_H
    
    #include <QDialog>
    
    class QProgressDialog;
    
    QT_BEGIN_NAMESPACE
    namespace Ui { class Dialog; }
    QT_END_NAMESPACE
    
    class Dialog : public QDialog
    {
        Q_OBJECT
    
    public:
        Dialog(QWidget *parent = nullptr);
        ~Dialog();
    
    private slots:
        void on_pushButton_clicked();
        void my_custom_cancel();
    
    private:
        Ui::Dialog *ui;
        QProgressDialog *progress;
        int numTasks = 100000;
        bool canceled = false;
    };
    #endif // DIALOG_H
    

    dialog.cpp

    #include "dialog.h"
    #include "ui_dialog.h"
    
    #include <QProgressDialog>
    #include <QThread>
    #include <QDebug>
    
    Dialog::Dialog(QWidget *parent)
        : QDialog(parent)
        , ui(new Ui::Dialog)
    {
        progress = new QProgressDialog("Task in progress...", "Cancel", 0, numTasks);
    
        connect(progress, SIGNAL(canceled()), this, SLOT(my_custom_cancel()));
    
        ui->setupUi(this);
    }
    
    Dialog::~Dialog()
    {
        delete ui;
    }
    
    void Dialog::on_pushButton_clicked()
    {
        progress->open();
    
        for (int i = 0; i < numTasks; i++) {
            progress->setValue(i);
            QThread::usleep(100);
            if (canceled)
                break;
        }
        progress->setValue(numTasks);
    }
    
    void Dialog::my_custom_cancel()
    {
        qDebug() << "do something";
    
        canceled = true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      相关资源
      最近更新 更多