Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
mainwindow.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3#include "mainwindow.h"
4
5#include <QMenu>
6#include <QMenuBar>
7#include <QTextEdit>
8#include <QFileDialog>
9#include <QPrinter>
10#include <QPrintDialog>
11
12MainWindow::MainWindow()
13{
14 QMenu *fileMenu = new QMenu(tr("&File"));
15
16 fileMenu->addAction(tr("&Open..."), QKeySequence(tr("Ctrl+O", "File|Open")),
17 this, SLOT(openFile()));
18
19 printAction = fileMenu->addAction(tr("&Print..."), this, SLOT(printFile()));
20 printAction->setEnabled(false);
21
22 pdfPrintAction = fileMenu->addAction(tr("Print as P&DF..."), this, SLOT(printPdf()));
23 pdfPrintAction->setEnabled(false);
24
25 fileMenu->addAction(tr("E&xit"), QKeySequence(tr("Ctrl+Q", "File|Exit")),
26 this, SLOT(close()));
27
28 menuBar()->addMenu(fileMenu);
29
30 editor = new QTextEdit(this);
31 document = new QTextDocument(this);
32 editor->setDocument(document);
33
34 connect(editor, &QTextEdit::selectionChanged, this, &MainWindow::updateMenus);
35
36 setCentralWidget(editor);
37 setWindowTitle(tr("Text Document Writer"));
38}
39
41{
42 QString fileName = QFileDialog::getOpenFileName(this,
43 tr("Open file"), currentFile, "HTML files (*.html);;Text files (*.txt)");
44
45 if (!fileName.isEmpty()) {
46 QFileInfo info(fileName);
47 if (info.completeSuffix() == "html") {
48 QFile file(fileName);
49
50 if (file.open(QIODevice::ReadOnly)) {
51 editor->setHtml(file.readAll());
52 file.close();
53 currentFile = fileName;
54 }
55 } else if (info.completeSuffix() == "txt") {
56 QFile file(fileName);
57
58 if (file.open(QIODevice::ReadOnly)) {
59 editor->setPlainText(file.readAll());
60 file.close();
61 currentFile = fileName;
62 }
63 }
64 printAction->setEnabled(true);
65 pdfPrintAction->setEnabled(true);
66 }
67}
68
70{
71//! [0]
72 QTextDocument *document = editor->document();
73 QPrinter printer;
74
75 QPrintDialog *dlg = new QPrintDialog(&printer, this);
76 if (dlg->exec() != QDialog::Accepted)
77 return;
78
79 document->print(&printer);
80//! [0]
81}
82
84{
85 QPrinter printer(QPrinter::HighResolution);
86 printer.setOutputFormat(QPrinter::PdfFormat);
87
88 QPrintDialog *printDialog = new QPrintDialog(&printer, this);
89 if (printDialog->exec() == QDialog::Accepted)
90 editor->document()->print(&printer);
91}
void openFile()
void printFile()
void printPdf()