选择文件后 QSignalMapper 不更新参数

QSignalMapper does not update parameter after choosing file

我正在制作一个可以对我的电路板进行编程的应用程序。我想通过文件对话框 select 文件并通过上传按钮用 selected 文件上传板。我有两个 class:MyFileDialog 和 CommandProcess。我将上传按钮点击信号连接到信号映射器,并将其映射到 CommandProcess::startProcess 插槽,该插槽执行具有 selected 文件路径的进程,但如果我在程序启动时未指明路径,则该路径不正确.选择文件后如何更新映射参数?

部分main.cpp代码:

QObject *uploadButton = mainForm->findChild<QObject*>("uploadButton");

QSignalMapper mapper;
ConsoleProcess proc;
MyFileDialog mfd;

QObject::connect(fileButton, SIGNAL(clicked()), &mfd, SLOT(openMyFileDialog()));
QObject::connect(uploadButton, SIGNAL(clicked()), &mapper, SLOT(map()));
mapper.setMapping(uploadButton, mfd.getFilename());
QObject::connect(&mapper, SIGNAL(mapped(const QString &)),&proc, SLOT(startProcess(const QString &))); 

MyFileDialogclass:

public:
    MyFileDialog();
    QString getFilename();

private:
    QFileDialog fd; 

public slots:
    void openMyFileDialog();

QString MyFileDialog::getFilename()   {
    return fd.getOpenFileName();
}

控制台进程class:

private:
    QProcess p;

public:
    ConsoleProcess();

public slots:
    void startProcess(const QString &);

void ConsoleProcess::startProcess(const QString & path) {
    p.setWorkingDirectory("C:/avrdude");
    p.start("cmd.exe /C start avrdude.exe -c breakout -P ft0 -p m2560 -U flash:w:\"" + path + "\":a");
}

您可以在 MainWindow class 和 QString 成员处创建 2 个槽,用于存储文件路径,如下所示:

class MainWindow : public QMainWindow, private Ui::MainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

public slots:
    void choseSlot();
    void uploadSlot();

private:
    QString m_file;

};

在构造函数中创建连接 class 并初始化 m_file 变量:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), m_file(QString())
{
    setupUi(this);

    connect(choseFile,  SIGNAL(clicked(bool)), this, SLOT(choseSlot()));
    connect(uploadFile, SIGNAL(clicked(bool)), this, SLOT(uploadSlot()));
}

然后是时候实现所描述的插槽了。让我们得到 QFileDialog::getOpenFileName 静态方法结果:

void MainWindow::choseSlot()
{
    m_file = QFileDialog::getOpenFileName(this, tr("Open file"), QDir::currentPath(), tr("Some Files (*.a *.b *.c)"));
}

如果文件已经在上传位置选择,我们可以传输它们或做任何你想做的事:

void MainWindow::uploadSlot()
{
    if (!m_file.isEmpty()) {
        qDebug() << Q_FUNC_INFO << m_file;
        QProcess *prc = new QProcess;
        connect(prc, SIGNAL(finished(int)), prc, SLOT(deleteLater()));
        prc->setWorkingDirectory("C:/avrdude");
        prc->start("cmd.exe /C start avrdude.exe -c breakout -P ft0 -p m2560 -U flash:w:\"" + m_file + "\":a");
    }
}