选择文件后,QSignalMapper不会更新参数

时间:2015-07-27 12:26:50

标签: c++ qt signals-slots qfiledialog qsignalmapper

我正在制作一个可以对我的电路板进行编程的应用程序。我想通过文件对话框选择文件,并通过上传按钮上传选定文件的板。我有两个类: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();
}

ConsoleProcess类:

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

1 个答案:

答案 0 :(得分: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()));
}

然后是时候实现所描述的插槽。让我们得到never use query_posts()静态方法结果:

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