使用线程执行QFile::copy时,怎样停止文件的复制,我使用锁停止线程无法做到
2条回答 默认 最新
- 北海 2023-02-09 11:25关注
你可以在线程中设置一个标志位,然后在复制过程中进行检查以判断该标志的值,决定是否停止复制
#include <QFile> #include <QThread> class CopyThread : public QThread { Q_OBJECT public: CopyThread(const QString &source, const QString &destination) : m_source(source) , m_destination(destination) , m_stop(false) { } void stop() { m_stop = true; } protected: void run() { QFile file(m_source); if (file.open(QIODevice::ReadOnly)) { QFile destination(m_destination); if (destination.open(QIODevice::WriteOnly)) { char buffer[1024]; qint64 readBytes = 0; while ((readBytes = file.read(buffer, 1024)) > 0 && !m_stop) { destination.write(buffer, readBytes); } destination.close(); } file.close(); } } private: QString m_source; QString m_destination; volatile bool m_stop; };
比如上面的代码,需要停止复制时调用 stop 函数就可以了
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报