我正在通过QThread
以下方式进行打印工作QPrinter
我的PrintWorker
样子是这样的:
class PrintWorker : public QObject {
Q_OBJECT
public:
PrintWorker(QThread*, QPrinter*, QPicture*, QPainter*, QObject *parent = 0);
private:
QPicture *_picture = nullptr;
QPrinter *_printer = nullptr;
QPainter *_painter = nullptr;
public slots:
void print();
signals:
void done();
};
PrintWorker::PrintWorker(QThread *thread, QPrinter *printer, QPicture *picture, QPainter *painter, QObject *parent) :QObject(parent),
_picture(picture), _printer(printer), _painter(painter)
{
moveToThread(thread);
QObject::connect(thread, &QThread::started, this, &PrintWorker::print);
QObject::connect(this, &PrintWorker::done, thread, &QThread::quit);
QObject::connect(this, &PrintWorker::done, this, &PrintWorker::deleteLater);
QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater);
}
void PrintWorker::print() {
// do some print job with painter and picture
emit done();
}
print
方法是这样的:
void NewService::print() {
if (!_printer) { /* _printer : a private member */
_printer = new QPrinter(QPrinter::HighResolution);
_printer->setPageSize(QPrinter::A5);
_printer->setPageOrientation(QPageLayout::Portrait);
_printer->setColorMode(QPrinter::Color);
}
if (!_printDialog) { /* _printDialog : a private member */
_printDialog = new QPrintDialog(_printer);
}
if (_printDialog->exec() == QPrintDialog::Accepted) {
MyWidget *widget = new MyWidget(/* some args*/);
QPainter *painter = new QPainter;
QPicture *picture = new QPicture;
widget->render(picture);
QThread *thread = new QThread;
PrintWorker *worker = new PrintWorker(thread, _printer, picture, painter);
thread->start();
}
}
现在在调用我的应用程序之前,在打印和调用我的应用程序的内存使用量达到 26MBprint()
之后会暴露大约 9MB 的内存PrintWorker::print()
在另一个世界中,如果我们删除emit done
最后一部分,PrintWorker::print()
它没有任何区别。
完成工作后我们期望内存使用量应降至 26MB - 线程空间 + _printer
+_printDialog
对象大小 ≈ 14MB
那么这有什么问题呢?