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 ?
CodePudding user response:
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.";
}
}
CodePudding user response:
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.";
}
}
CodePudding user response:
Why are you trying to create a list of QFile
? Perhaps you can just store QString
paths and then create QFile
when needed:
QVector<QString> filePathsList;
filePathsList << QStringLiteral("path/to/file_1"));
filePathsList << QStringLiteral("path/to/file_2"));
for (auto &filePath : qAsConst(filePathsList)) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "file is not open.";
}
}
CodePudding user response:
I have no experience with Qt, but 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.";
}
}