-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelper.cpp
More file actions
58 lines (48 loc) · 1.52 KB
/
helper.cpp
File metadata and controls
58 lines (48 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// helper.cpp
#include "helper.h"
#include <QPrinter>
#include <QPainter>
#include <QPrintDialog>
#include <QPixmap>
#include <QDebug>
#include <QImage>
#include <QQuickItemGrabResult>
#include <QSharedPointer>
Printer::Printer(QObject *parent) : QObject(parent)
{
}
void Printer::print(QQuickWindow* window)
{
if (!window) {
qWarning() << "Error: Window is null.";
return;
}
window->setProperty("isPrintMode", true);
window->contentItem()->update();
window->update();
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
QImage image = window->grabWindow();
window->setProperty("isPrintMode", false);
if (image.isNull()) {
qWarning() << "Error: Failed to grab window content.";
return;
}
QPrinter printer(QPrinter::HighResolution);
QPrintDialog dialog(&printer, nullptr);
if (dialog.exec() != QDialog::Accepted) {
return;
}
QPainter painter(&printer);
if (!painter.isActive()) {
qWarning() << "Error: Failed to activate painter for printer.";
return;
}
QRectF pageRect = printer.pageRect(QPrinter::DevicePixel);
QPixmap pixmap = QPixmap::fromImage(image);
QSize imageSize = pixmap.size();
imageSize.scale(pageRect.size().toSize(), Qt::KeepAspectRatio);
int x = pageRect.x() + (pageRect.width() - imageSize.width()) / 2;
int y = pageRect.y() + (pageRect.height() - imageSize.height()) / 2;
painter.drawPixmap(QRect(x, y, imageSize.width(), imageSize.height()), pixmap);
painter.end();
}