繁体   English   中英

如何制作QFiles的列表(QList)? 它是如何工作的?

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

我正在尝试列出QFiles ,我选择了QList方法,但不确定它是否是好的方法。 我写了这段代码,但它无法构建!

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

构建失败并出现此错误:

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

使用QList方法制作文件列表以备后用是否好? 如果是这样,如何修复我的代码?

看起来问题是 QFile class 有一个私有的复制构造函数,这意味着它不能被复制。 因此,不能像QList那样存放在容器中。 解决此问题的一种方法是在 QList 中存储指向 QFile 对象的指针而不是对象本身。

尝试这个:

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

更新后的版本:

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

感谢@Fareanor 的评论,我通过为路径制作 QString 列表解决了这个问题,并且在打开文件时使用了 QFile:

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

你为什么要创建一个QFile列表? 也许您可以只存储QString路径,然后在需要时创建QFile

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

如果你想要 QFile 的 QList,为什么不放置元素呢?。 无需在外部创建它们并在可以就地创建它们时复制它们:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM