How to make a list(QList) of QFiles? and how it works?

181 Views Asked by At

I am trying to make a list of QFiles, I went for the QList approach but am not sure if it is good approach or not. I write this code but it fails to build!

QList<QFile> filesList;

QFile file_1(QString("path/to/file_1"));
QFile file_2(QString("path/to/file_2"));

filesList.append(file_1);
filesList.append(file_2);

    for(auto& file : filesList){
        if(!file.open(QIODevice::ReadOnly)){
            qDebug() << "file is not open.";
        }
}

The build failed with this error:

error: ‘QFile::QFile(const QFile&)’ is private within this context
     if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t);
                                                                 ^~~~~~~~

Is it good to use QList approach of making a list of files to use later? if so, how to fix my code ?

3

There are 3 best solutions below

20
Daniel On BEST ANSWER

It looks like the issue is that the QFile class has a private copy constructor, which means that it cannot be copied. Therefore, it cannot be stored in a container like QList. One way to work around this issue is to store pointers to QFile objects in the QList instead of the objects themselves.

Try this:

QList<QFile*> filesList;

QFile* file_1 = new QFile(QString("path/to/file_1"));
QFile* file_2 = new QFile(QString("path/to/file_2"));

filesList.append(file_1);
filesList.append(file_2);

for(auto file : filesList){
    if(!file->open(QIODevice::ReadOnly)){
        qDebug() << "file is not open.";
    }
}

Updated version:

QList<QFile> filesList;

QFile file_1("path/to/file_1");
QFile file_2("path/to/file_2");

filesList.append(file_1);
filesList.append(file_2);

for(auto& file : filesList){
    if(!file.open(QIODevice::ReadOnly)){
        qDebug() << "file is not open.";
    }
}
1
A.A. On

thanks to @Fareanor comment, I solved this by making a list of QString for the paths and I used QFile when I open the file:

QList<QString> filesList;

filesList.append("path/to/file_1");
filesList.append("path/to/file_2");

    for(auto& path : filesList){
        QFile file(path);
        if(!file.open(QIODevice::ReadOnly)){
            qDebug() << "file is not open.";
        }
}
1
cptFracassa On

If you want the QList of QFile, why not emplacing the elements?. No need for creating them outside and copying them in when they can be created in-place:

QList<QFile> filesList;

filesList.emplaceBack(QString("path/to/file_1"));
filesList.emplaceBack(QString("path/to/file_2"));

for(auto& file : filesList){
    if(!file.open(QIODevice::ReadOnly)){
        qDebug() << "file is not open.";
    }
}