簡體   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