Size of file in bytes in QTreeView



  • Help!

    How can I show size of files in bytes in QTreeView?

    Now it show in KB or GB.



  • Hi there, the QFileInfo class gives the size in bytes. How do you use the QTreeView? What model is connected to it?
    Bit of code would help.



  • Sorry for rude english.

    I do it like this:
    @
    QDirModel* model = new QDirModel(this);

    ui->treeView->setModel(model->index(dir));
    ui->treeView->setRootIndex(index);
    @

    I've tried many ways, but have no answer.

    Later I find in Qt source code, that in qdirmodel.cpp lie this awful thing:
    @
    QString QDirModelPrivate::size(const QModelIndex &index) const
    {
    const QDirNode *n = node(index);
    if (n->info.isDir()) {
    #ifdef Q_OS_MAC
    return QLatin1String("--");
    #else
    return QLatin1String("");
    #endif
    // Windows - ""
    // OS X - "--"
    // Konqueror - "4 KB"
    // Nautilus - "9 items" (the number of children)
    }

    // According to the Si standard KB is 1000 bytes, KiB is 1024
    // but on windows sizes are calulated by dividing by 1024 so we do what they do.
    const quint64 kb = 1024;
    const quint64 mb = 1024 * kb;
    const quint64 gb = 1024 * mb;
    const quint64 tb = 1024 * gb;
    quint64 bytes = n->info.size();
    if (bytes >= tb)
        return QFileSystemModel::tr("%1 TB").arg(QLocale().toString(qreal(bytes) / tb, 'f', 3));
    if (bytes >= gb)
        return QFileSystemModel::tr("%1 GB").arg(QLocale().toString(qreal(bytes) / gb, 'f', 2));
    if (bytes >= mb)
        return QFileSystemModel::tr("%1 MB").arg(QLocale().toString(qreal(bytes) / mb, 'f', 1));
    if (bytes >= kb)
        return QFileSystemModel::tr("%1 KB").arg(QLocale().toString(bytes / kb));
    return QFileSystemModel::tr("%1 byte(s)").arg(QLocale().toString(bytes));
    

    }
    @

    And no way, only rebild Qt.



  • QString sizeFormat(quint64 size)
    {
        qreal calc = size;
        QStringList list;
        list << "KB" << "MB" << "GB" << "TB";
    
        QStringListIterator i(list);
        QString unit("byte(s)");
    
        while(calc >= 1024.0 && i.hasNext())
        {
            unit = i.next();
            calc /= 1024.0;
        }
    
        return QString().setNum(calc, 'f', 2) + " " + unit;
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.