0

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

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 &))); 

MyFileDialog 类:

public:
    MyFileDialog();
    QString getFilename();

private:
    QFileDialog fd; 

public slots:
    void openMyFileDialog();

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

控制台进程类:

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");
}
4

1 回答 1

1

您可以在您的MainWindow班级和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;

};

在构造函数类中创建连接并初始化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");
    }
}
于 2015-07-27T14:49:26.193 回答