Search code examples
c++qtqt4qt4.8

Declaring QStringlist variable globally, Getting location path using QFileDialog and printing it to a lineEdit and using it in QProcess


I am using Qt and I need some help

  1. How to declare QStringList variable globally in Qt so that I can access it in any function?

  2. How to print all the stuff in QStringList(it contains the file path which it took from QFileDialog) to a lineEdit?

I tried:

ui->lineEdit->setText(filename);

But it gave me error error:QString to non-scalar type QStringList requested. Please give me some examples.


Solution

  • How to declare QStringList variable globally in Qt so that I can access it in any function

    Well this isn't a Qt question, but a general C++ one (global variables are frowned upon these days, a more acceptable equivalent is the singleton, search SO for lots of examples). Nonetheless, one way of doing this would be create the QStringList as a static member of the class that instantiates the QFileDialog, the same class will be the one that retrieved it from the dialog anyway and by storing (and returning) it statically you effectively make it global:

    class A
    {
    public:
        void openFileDialog() { // Open the dialog, and store the results in list_. }
        static const QStringList& getFileList() { return list_; }
    private:
        static list_;
    }
    
    // Just call by:
    QStringList list = A::getFileList();
    

    How to print all the stuff in QStringList(it contains the file path which it took from QFileDialog)

    Yes, my QStringList contains only 1 string

    Well, if your QStringList only contains one string just use:

    ui->lineEdit->setText(list_[0]);
    

    Remember a QStringList is derived from QVector< QString >, so you can access the individual QStrings just like any element.

    Just to expand your first question, there an infinite number of ways a list of strings can be combined into a single one. But a very common (and easy) method with QStringList is to use join():

    QStringList list; list << "This" << "is" << "a" << "list.";
    list.join( " " ); // "This is a list. "
    

    I really recommend using the docs, Qt's are brilliant .