Qt/C++ 如何断开 QProgressDialog::canceled 信号与其 QProgressDialog::cancel 插槽的连接?

Qt/C++ How can I disconnect a QProgressDialog::canceled signal to its QProgressDialog::cancel slot?

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

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

我尝试断开 canceled/cancel signal/slot 对的连接并重新连接新行为,但它似乎没有太大变化。

只要我点击取消按钮,进度对话框就会先关闭,然后我的 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();
});

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

我不知道你的整个代码,但是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;
}