Passing a variable to other dialog Qt

本小妞迷上赌 提交于 2019-12-11 07:40:51

问题


I have a QTreeView with a list of text files. If a file is selected and void FileList_dialog::on_openButton_released() it should pass a variable pathto dialog textFile_dialog.

Until now I've this:

void FileList::on_openButton_released()
{
    QModelIndex index = ui->treeView->currentIndex();
    QFileSystemModel *model = (QFileSystemModel*)ui->treeView->model();
    QString path = model->filePath(index);
    QString name = model->fileName(index);
    QString dir = path;
    QFile file(path);
    qDebug() << path;

    textFile_dialog textFile;
    textFile.setModal(true);
    textFile.exec();
}

But how do I pass the variable path to textFile_dialog?


回答1:


You have have several options:

1) Pass the path to the dialog constructor

The code would look something like this:

textfile_dialog.h

class TextFile_Dialog : public QDialog 
{
    Q_OBJECT
    public:
        explicit TextFile_Dialog(const QString &path, QObject *parent = 0);
    ...
    private:
        QString m_path;
};

textfile_dialog.cpp

...

#include "textfile_dialog.h"

...

TextFile_Dialog::TextFileDialog(const QString &path, QObject *parent)
    : QDialog(parent)
    , m_path(path)
{
    ...
}

...

Then you would use the class like this:

textFile_dialog textFile_Dialog(path);

2) You could also have a setter method for setting the path as follows:

textfile_dialog.h

class TextFile_Dialog : public QDialog 
{
    Q_OBJECT
    public:
    ...
        void setPath(const QString &path);
    ...
    private:
        QString m_path;
};

textfile_dialog.cpp

...

#include "textfile_dialog.h"

...

void TextFile_Dialog::setPath(const QString &path)
{
    m_path = path;
}

...

Then the usage would be like this:

textFile_dialog textFile_Dialog;
textFile_Dialog.setPath(path);



回答2:


In the header of the textFile_dialog class, you add a parameter to the constructor:

explicit textFile_dialog(const QString &a_path);

and in the FileList::on_openButton_released() change the constructor call to:

textFile_dialog textFile(path);


来源:https://stackoverflow.com/questions/20948665/passing-a-variable-to-other-dialog-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!