Qfile и qthreadpool: отзывчивое чтение файлов
Содержание:
mainwindow.ui
На этот раз в формочку главного окна необходимо добавить достаточно большое количество элементов, чтобы оно стало выглядеть следующим образом:
-

- Главное окно приложения для работы с XML файлом
Список всех элементов, с которыми будет производиться работа в программном коде:
-
checkBox —
первый чекбокс;
-
checkBox_1 —
второй чекбокс;
-
checkBox_2
— третий чекбокс;
-
lineEditCB1 —
lineEdit для первого чекбокса;
-
lineEditCB2 —
lineEdit для второго чекбокса;
-
lineEditCB3
— lineEdit для третьего чекбокса;
-
lineEditRead
— lineEdit, в котором указывается путь к файлу для чтения;
-
lineEditWrite
— lineEdit, в котором указывается путь к файлу для записи;
-
dialogReadButton
— кнопка для вызова диалога сохранения файла, в данном случае выполняется просто выбор файла, с которым будет производиться работа;
-
dialogButton
— кнопка для вызова диалога записи файла, в данном случае выполняется просто выбор файла, с которым также будет производиться работа;
-
readButton
— кнопка выполнения чтения из файла;
-
generateButton
— кнопка для выполнения записи в файл.
Detailed Description
QFileInfo provides information about a file’s name and position
(path) in the file system, its access rights and whether it is a
directory or symbolic link, etc. The file’s size and last
modified/read times are also available.
A QFileInfo can point to a file with either a relative or an
absolute file path. Absolute file paths begin with the directory
separator «/» (or with a drive specification on Windows). Relative
file names begin with a directory name or a file name and specify
a path relative to the current working directory. An example of an
absolute path is the string «/tmp/quartz». A relative path might
look like «src/fatlib». You can use the function () to
check whether a QFileInfo is using a relative or an absolute file
path. You can call the function () to convert a
relative QFileInfo’s path to an absolute path.
The file that the QFileInfo works on is set in the constructor or
later with (). Use () to see if the file exists and
() to get its size.
To speed up performance, QFileInfo caches information about the
file. Because files can be changed by other users or programs, or
even by other parts of the same program, there is a function that
refreshes the file information: (). If you want to switch
off a QFileInfo’s caching and force it to access the file system
every time you request information from it call (FALSE).
The file’s type is obtained with (), () and
(). The () function provides the name of the file
the symlink points to.
Elements of the file’s name can be extracted with () and
(). The fileName()’s parts can be extracted with
() and ().
The file’s dates are returned by (), () and
(). Information about the file’s access permissions is
obtained with (), () and (). The
file’s ownership is available from (), (), () and
(). You can examine a file’s permissions and ownership in a
single statement using the () function.
If you need to read and traverse directories, see the QDir class.
See also Input/Output and Networking.
const QFileInfoList * QDir::entryInfoList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [virtual]
Returns a list of QFileInfo objects for all the files and directories in the directory, ordered in accordance with setSorting() and filtered in accordance
with setFilter() and setNameFilter().
The filter and sorting specifications can be overridden using the nameFilter, filterSpec and sortSpec arguments.
Returns 0 if the directory is unreadable or does not exist.
The returned pointer is a const pointer to a QFileInfoList. The list is owned by the QDir object and will be reused on the next call to entryInfoList() for
the same QDir instance. If you want to keep the entries of the list after a subsequent call to this function you must copy them.
Note: QFileInfoList is really a QPtrList<QFileInfo>.
See also entryList(), setNameFilter(), setSorting(), and setFilter().
Examples:
mainwindow.h
В заголовочном файле подключаются библиотеки для работы с
QXmlStreamWriter
и
QXmlStreamReader.
Также объявляются слоты обработчиков нажатий кнопок.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QXmlStreamAttribute>
#include <QMessageBox>
#include <QFile>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
/* Слоты обработчиков кнопок, работающих с записью в файл */
void on_generateButton_clicked();
void on_dialogButton_clicked();
/* Слоты обработчиков кнопок, работающих с чтением из файла */
void on_readButton_clicked();
void on_dialogReadButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
bool QDir::rename ( const QString & oldName, const QString & newName, bool acceptAbsPaths = TRUE ) [virtual]
Renames a file or directory.
If acceptAbsPaths is TRUE a path starting with a separator (‘/’) will rename the file with the absolute path; if acceptAbsPaths is FALSE any
number of separators at the beginning of the names will be removed.
Returns TRUE if successful; otherwise returns FALSE.
On most file systems, rename() fails only if oldName does not exist or if newName and oldName are not on the same partition. On
Windows, rename() will fail if newName already exists. However, there are also other reasons why rename() can fail. For example, on at least one file
system rename() fails if newName points to an open file.
Example: fileiconview/qfileiconview.cpp.
Bugs
If you find a bug in Qt, please report it as described in http://doc.trolltech.com/bughowto.html. Good bug reports help us to help you. Thank you.
The definitive Qt documentation is provided in HTML format; it is located at $QTDIR/doc/html and can be read using Qt Assistant or with a web browser. This
man page is provided as a convenience for those users who prefer man pages, although this format is not officially supported by Trolltech.
If you find errors in this manual page, please report them to qt-bugs@trolltech.com. Please include the name of the manual page (qdir.3qt) and the Qt
version (3.3.8).
mainwindow.h
В заголовочном файле подключаются библиотеки для работы с
QXmlStreamWriter
и
QXmlStreamReader.
Также объявляются слоты обработчиков нажатий кнопок.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QXmlStreamAttribute>
#include <QMessageBox>
#include <QFile>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
/* Слоты обработчиков кнопок, работающих с записью в файл */
void on_generateButton_clicked();
void on_dialogButton_clicked();
/* Слоты обработчиков кнопок, работающих с чтением из файла */
void on_readButton_clicked();
void on_dialogReadButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Member Function Documentation
QResource::QResource(const QString &file = QString(), const QLocale &locale = QLocale())
Constructs a QResource pointing to file. locale is used to load a specific localization of a resource data.
See also QFileInfo, (), (), and ().
QString QResource::absoluteFilePath() const
Returns the real path that this QResource represents, if the resource was found via the () it will be indicated in the path.
See also ().
Returns a list of all resources in this directory, if the resource represents a file the list will be empty.
See also ().
QResource::compressionAlgorithm() const
Returns the compression type that this resource is compressed with, if any. If it is not compressed, this function returns .
If this function returns , you may decompress the data using the () function. Up until Qt 5.13, this was the only possible compression algorithm.
If this function returns , you need to use the Zstandard library functios (
This function was introduced in Qt 5.13.
const *QResource::data() const
Returns direct access to a segment of read-only data, that this resource represents. If the resource is compressed, the data returned is also compressed. The caller must then decompress the data or use (). If the resource is a directory, is returned.
See also (), (), and ().
Returns the full path to the file that this QResource represents as it was passed.
See also () and ().
Returns if the resource represents a directory and thus may have () in it, false if it represents a file.
See also ().
Returns if the resource represents a file and thus has data backing it, false if it represents a directory.
See also ().
QDateTime QResource::lastModified() const
Returns the date and time when the file was last modified before packaging into a resource.
This function was introduced in Qt 5.8.
Returns the locale used to locate the data for the QResource.
See also ().
Registers the resource with the given rccFileName at the location in the resource tree specified by mapRoot, and returns if the file is successfully opened; otherwise returns .
See also ().
bool QResource::registerResource(const *rccData, const QString &mapRoot = QString())
Registers the resource with the given rccData at the location in the resource tree specified by mapRoot, and returns if the file is successfully opened; otherwise returns .
Warning: The data must remain valid throughout the life of any QFile that may reference the resource data.
This function was introduced in Qt 4.3.
See also ().
void QResource::setFileName(const QString &file)
Sets a QResource to point to file. file can either be absolute, in which case it is opened directly, if relative then the file will be tried to be found in ().
See also () and ().
void QResource::setLocale(const QLocale &locale)
Sets a QResource to only load the localization of resource to for locale. If a resource for the specific locale is not found then the C locale is used.
See also () and ().
QResource::size() const
Returns the size of the stored data backing the resource.
If the resource is compressed, this function returns the size of the compressed data. See () for the uncompressed size.
See also (), (), and ().
QByteArray QResource::uncompressedData() const
Returns the resource data, decompressing it first, if the data was stored compressed. If the resource is a directory or an error occurs while decompressing, a null QByteArray is returned.
Note: If the data was compressed, this function will decompress every time it is called. The result is not cached between calls.
This function was introduced in Qt 5.15.
See also (), (), (), and ().
QResource::uncompressedSize() const
Returns the size of the data in this resource. If the data was not compressed, this function returns the same as (). If it was, then this function extracts the size of the original uncompressed data from the stored stream.
This function was introduced in Qt 5.15.
See also (), (), and ().
Unregisters the resource with the given rccFileName at the location in the resource tree specified by mapRoot, and returns if the resource is successfully unloaded and no references exist for the resource; otherwise returns .
See also ().
bool QResource::unregisterResource(const *rccData, const QString &mapRoot = QString())
Unregisters the resource with the given rccData at the location in the resource tree specified by mapRoot, and returns if the resource is successfully unloaded and no references exist into the resource; otherwise returns .
This function was introduced in Qt 4.3.
See also ().
Bugs
If you find a bug in Qt, please report it as described in http://doc.trolltech.com/bughowto.html. Good bug reports help us to help you. Thank you.
The definitive Qt documentation is provided in HTML format; it is located at $QTDIR/doc/html and can be read using Qt Assistant or with a web browser. This
man page is provided as a convenience for those users who prefer man pages, although this format is not officially supported by Trolltech.
If you find errors in this manual page, please report them to qt-bugs@trolltech.com. Please include the name of the manual page (qfileinfo.3qt) and
the Qt version (3.3.8).
Member Function Documentation
file
See also (), (), () and ().
file
If the file has a relative path, the QFileInfo will also have a
relative path.
fileNamed
If the directory has a relative path, the QFileInfo will also have a
relative path.
QString QFileInfo::absFilePath () const
The absolute path name consists of the full path and the file
name. On Unix this will always begin with the root, ‘/’, directory.
On Windows this will always begin ‘D:/’ where D is a drive
letter, except for network shares that are not mapped to a drive
letter, in which case the path will begin ‘//sharename/’.
This function returns the same as (), unless () is
TRUE.
This function can be time consuming under Unix (in the order of
milliseconds).
QString QFileInfo::baseName ( bool complete = FALSE ) const
If complete is FALSE (the default) the base name consists of all
characters in the file name up to (but not including) the first ‘.’
character.
If complete is TRUE the base name consists of all characters in the
file up to (but not including) the last ‘.’ character.
The path is not included in either case.
Example:
QFileInfo fi( "/tmp/archive.tar.gz" );
QString base = fi.(); // base = "archive"
base = fi.( TRUE ); // base = "archive.tar"
If it is already absolute, nothing is done.
On platforms where this information is not available, returns the
same as ().
QDir QFileInfo::dir ( bool absPath = FALSE ) const
If the QFileInfo is relative and absPath is FALSE, the QDir will be
relative; otherwise it will be absolute.
See also (), (), () and ().
Example: .
If absPath is TRUE an absolute path is returned.
See also (), (), () and ().
Example: .
QString QFileInfo::extension ( bool complete = TRUE ) const
If complete is TRUE (the default), () returns the string
of all characters in the file name after (but not including) the
first ‘.’ character.
If complete is FALSE, extension() returns the string of all
characters in the file name after (but not including) the last ‘.’
character.
Example:
QFileInfo fi( "/tmp/archive.tar.gz" );
QString ext = fi.(); // ext = "tar.gz"
ext = fi.( FALSE ); // ext = "gz"
Example: .
QString QFileInfo::fileName () const
Example:
QFileInfo fi( "/tmp/archive.tar.gz" );
QString name = fi.(); // name = "archive.tar.gz"
See also (), (), () and ().
This function can be time consuming under Unix (in the order of
milliseconds).
On Windows and on systems where files do not have groups this function
always returns (uint) -2.
Examples: , and .
Example: .
On platforms where this information is not available, returns the
same as ().
Example: .
This function can be time consuming under Unix (in the order of
milliseconds).
On Windows and on systems where files do not have owners this function
returns ((uint) -2).
bool QFileInfo::permission ( int permissionSpec ) const
Tests for file permissions. The permissionSpec argument can be several
flags of type PermissionSpec OR-ed together to check for permission
combinations.
On systems where files do not have permissions this function always
returns TRUE.
Example:
QFileInfo fi( "/tmp/archive.tar.gz" );
if ( fi.( QFileInfo:: | QFileInfo:: ) )
( "I can change the file; my group can read the file.");
if ( fi.( QFileInfo:: | QFileInfo:: ) )
( "The group or others can change the file!" );
QString QFileInfo::readLink () const
QString
This name may not represent an existing file; it is only a string.
() returns TRUE if the symlink points to an
existing file.
See also (), (), () and ().
void QFileInfo::setCaching ( bool enable )
enableenable
When caching is enabled, QFileInfo reads the file information from the
file system the first time it’s needed, but generally not later.
Caching is enabled by default.
void QFileInfo::setFile ( const QString & file )
file
The string given can be an absolute or a relative file path. Absolute
paths begin with the directory separator (e.g. «/» under Unix) or a drive
specification (not applicable to Unix). Relative file names begin with a
directory name or a file name and specify a path relative to the current
directory.
Example:
QString absolute = "/local/bin";
QString relative = "local/bin";
QFileInfo absFile( absolute );
QFileInfo relFile( relative );
QDir::( QDir::() );
// absFile and relFile now point to the same file
QDir::( "/tmp" );
// absFile now points to "/local/bin",
// while relFile points to "/tmp/local/bin"
Example: .
void QFileInfo::setFile ( const QFile & file )
Sets the file that the QFileInfo provides information about to file.
If the file has a relative path, the QFileInfo will also have a
relative path.
void QFileInfo::setFile ( const QDir & d, const QString & fileName )
Sets the file that the QFileInfo provides information about to fileName in directory d.
If the file has a relative path, the QFileInfo will also have a
relative path.
Member Type Documentation
enum QFileSystemModel::Optionflags QFileSystemModel::Options
| Constant | Value | Description |
|---|---|---|
| Do not add file watchers to the paths. This reduces overhead when using the model for simple tasks like line edit completion. | ||
| Don’t resolve symlinks in the file system model. By default, symlinks are resolved. | ||
| Always use the default directory icon. Some platforms allow the user to set a different icon. Custom icon lookup causes a big performance impact over network or removable drives. This sets the option in the icon provider accordingly. |
This enum was introduced or modified in Qt 5.14.
The Options type is a typedef for QFlags<Option>. It stores an OR combination of Option values.
See also .
Member Function Documentation
This signal is emitted when the gatherer thread has finished to load the path.
This function was introduced in Qt 4.7.
Reimplements: (const QModelIndex &index, int role) const.
See also ().
bool QFileSystemModel::dropMimeData(const QMimeData *data, action, int row, int column, const QModelIndex &parent)
Reimplements: (const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent).
Handles the data supplied by a drag and drop operation that ended with the given action over the row in the model specified by the row and column and by the parent index. Returns true if the operation was successful.
See also ().
QFileSystemModel::filter() const
Returns the filter specified for the directory model.
If a filter has not been set, the default filter is | | .
See also () and .
QVariant QFileSystemModel::headerData(int section, orientation, int role = Qt::DisplayRole) const
Returns the file icon provider for this directory model.
See also ().
This is an overloaded function.
Returns the model item index for the given path and column.
QMimeData *QFileSystemModel::mimeData(const &indexes) const
Reimplements: (const QModelIndexList &indexes) const.
Returns an object that contains a serialized description of the specified indexes. The format used to describe the items corresponding to the indexes is obtained from the () function.
If the list of indexes is empty, is returned rather than a serialized empty list.
Returns a list of MIME types that can be used to describe a list of items in the model.
Returns the data stored under the given role for the item «My Computer».
See also .
Returns a list of filters applied to the names in the model.
See also ().
bool QFileSystemModel::remove(const QModelIndex &index)
Removes the model item index from the file system model and deletes the corresponding file from the file system, returning true if successful. If the item cannot be removed, false is returned.
Warning: This function deletes files from the file system; it does not move them to a location where they can be recovered.
See also ().
bool QFileSystemModel::rmdir(const QModelIndex &index)
Removes the directory corresponding to the model item index in the file system model and deletes the corresponding directory from the file system, returning true if successful. If the directory cannot be removed, false is returned.
Warning: This function deletes directories from the file system; it does not move them to a location where they can be recovered.
See also ().
The currently set directory
See also ().
The currently set root path
See also () and ().
Reimplements: (const QModelIndex &index, const QVariant &value, int role).
See also ().
void QFileSystemModel::setFilter( filters)
Sets the directory model’s filter to that specified by filters.
Note that the filter you set should always include the enum value, otherwise QFileSystemModel won’t be able to read the directory structure.
See also () and .
Sets the provider of file icons for the directory model.
See also ().
Sets the name filters to apply against the existing files.
See also ().
void QFileSystemModel::setOption( option, bool on = true)
Sets the given option to be enabled if on is true; otherwise, clears the given option.
Options should be set before changing properties.
This function was introduced in Qt 5.14.
See also and ().
QModelIndex QFileSystemModel::setRootPath(const QString &newPath)
Sets the directory that is being watched by the model to newPath by installing a file system watcher on it. Any changes to files and directories within this directory will be reflected in the model.
If the path is changed, the () signal will be emitted.
Note: This function does not change the structure of the model or modify the data available to views. In other words, the «root» of the model is not changed to include only files and directories within the directory specified by newPath in the file system.
See also ().
void QFileSystemModel::sort(int column, order = Qt::AscendingOrder)
bool QFileSystemModel::testOption( option) const
Returns if the given option is enabled; otherwise, returns false.
This function was introduced in Qt 5.14.
See also and ().
QDir::QDir ( const QString & path, const QString & nameFilter = QString::null, int sortSpec = Name | IgnoreCase, int filterSpec = All )
Constructs a QDir with path path, that filters its entries by name using nameFilter and by attributes using filterSpec. It also sorts
the names using sortSpec.
The default nameFilter is an empty string, which excludes nothing; the default filterSpec is All, which also means exclude nothing. The
default sortSpec is Name|IgnoreCase, i.e. sort by name case-insensitively.
Example that lists all the files in «/tmp»:
QDir d( "/tmp" );
for ( int i = 0; i < d.count(); i++ )
printf( "%s\n", d );
pathnameFilter
Note that path need not exist.
See also exists(), setPath(), setNameFilter(), setFilter(), and setSorting().
Дополнительные категории — QLoggingCategory
Дополнительные категории являются объектами класса
QLoggingCategory.
Может быть несколько подходов к работе с категориям, например, мы можем создать категорию объекта в каком-либо классе и передать его в сообщение об ошибке:
QLoggingCategory m_category("Test");
qDebug(m_category) << "Check it";
Получим следующий вывод:
Test: Check it
Неудобство данного подхода заключается в том, что несколько классов могут иметь одни и те же категории ошибок, но в каждом классе необходимо создавать одни и те же категории. Поэтому воспользуемся другим подходом. А именно регистрацией категории через макрос.
LoggingCategories.h
Мы объявим четыре категории в данном заголовочном классе.
#ifndef LOGGER_H #define LOGGER_H #include <QLoggingCategory> Q_DECLARE_LOGGING_CATEGORY(logDebug) Q_DECLARE_LOGGING_CATEGORY(logInfo) Q_DECLARE_LOGGING_CATEGORY(logWarning) Q_DECLARE_LOGGING_CATEGORY(logCritical) #endif // LOGGER_H
LoggingCategories.cpp
И присвоим имена данным категориям
#include "LoggingCategories.h" Q_LOGGING_CATEGORY(logDebug, "Debug") Q_LOGGING_CATEGORY(logInfo, "Info") Q_LOGGING_CATEGORY(logWarning, "Warning") Q_LOGGING_CATEGORY(logCritical, "Critical")
Использование LoggingCategories
Для того, чтобы применить данные категории, вы должны подключить заголовочный файл в тот файл, где будут использоваться данные категории. И затем использовать их:
qDebug(logDebug()) << "Check it";
Получим следующий вывод:
Debug: Check it
void QFileInfo::setFile ( const QString & file )
Sets the file that the QFileInfo provides information about to file.
The file can also include an absolute or relative file path. Absolute paths begin with the directory separator (e.g. «/» under Unix) or a drive
specification (under Windows). Relative file names begin with a directory name or a file name and specify a path relative to the current directory.
Example:
QString absolute = "/local/bin"; QString relative = "local/bin"; QFileInfo absFile( absolute ); QFileInfo relFile( relative ); QDir::setCurrent( QDir::rootDirPath() ); // absFile and relFile now point to the same file QDir::setCurrent( "/tmp" ); // absFile now points to "/local/bin", // while relFile points to "/tmp/local/bin"
Example: biff/biff.cpp.