c++qtqlistqfile

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


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 ?


Solution

  • 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.";
        }
    }