Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
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
4#include <QtWidgets>
5
6#include "mainwindow.h"
8{
9 textEdit = new QPlainTextEdit;
10 setCentralWidget(textEdit);
11
12 createActions();
13 createMenus();
14 createToolBars();
15 createStatusBar();
16
18
19 connect(textEdit->document(), &QTextEdit::contentsChanged,
20 this, &QAction::documentWasModified);
21
22 setCurrentFile(QString());
23 setUnifiedTitleAndToolBarOnMac(true);
24}
25
27{
28 if (maybeSave()) {
30 event->accept();
31 } else {
32 event->ignore();
33 }
34}
35
36void MainWindow::newFile()
37{
38 if (maybeSave()) {
39 textEdit->clear();
40 setCurrentFile(QString());
41 }
42}
43
44void MainWindow::open()
45{
46 if (maybeSave()) {
48 if (!fileName.isEmpty())
49 loadFile(fileName);
50 }
51}
52
53bool MainWindow::save()
54{
55 if (curFile.isEmpty()) {
56 return saveAs();
57 } else {
58 return saveFile(curFile);
59 }
60}
61
62bool MainWindow::saveAs()
63{
65 if (fileName.isEmpty())
66 return false;
67
68 return saveFile(fileName);
69}
70
71void MainWindow::about()
72{
73 QMessageBox::about(this, tr("About Application"),
74 tr("The <b>Application</b> example demonstrates how to "
75 "write modern GUI applications using Qt, with a menu bar, "
76 "toolbars, and a status bar."));
77}
78
79void MainWindow::documentWasModified()
80{
82}
83
84void MainWindow::createActions()
85{
86 newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
87 newAct->setShortcuts(QKeySequence::New);
88 newAct->setStatusTip(tr("Create a new file"));
89 connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
90
91 openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
92 openAct->setShortcuts(QKeySequence::Open);
93 openAct->setStatusTip(tr("Open an existing file"));
94 connect(openAct, &QAction::triggered, this, &MainWindow::open);
95
96 saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
97 saveAct->setShortcuts(QKeySequence::Save);
98 saveAct->setStatusTip(tr("Save the document to disk"));
99 connect(saveAct, &QAction::triggered, this, &MainWindow::save);
100
101 saveAsAct = new QAction(tr("Save &As..."), this);
102 saveAsAct->setShortcuts(QKeySequence::SaveAs);
103 saveAsAct->setStatusTip(tr("Save the document under a new name"));
104 connect(saveAsAct, &QAction::triggered, this, &MainWindow::saveAs);
105
106 exitAct = new QAction(tr("E&xit"), this);
107 exitAct->setShortcuts(QKeySequence::Quit);
108 exitAct->setStatusTip(tr("Exit the application"));
110
112 cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
114 cutAct->setShortcuts(QKeySequence::Cut);
115 cutAct->setStatusTip(tr("Cut the current selection's contents to the "
116 "clipboard"));
117 connect(cutAct, &QAction::triggered, textEdit, &QTextEdit::cut);
118
119 copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
120 copyAct->setShortcuts(QKeySequence::Copy);
121 copyAct->setStatusTip(tr("Copy the current selection's contents to the "
122 "clipboard"));
123 connect(copyAct, &QAction::triggered, textEdit, &QTextEdit::copy);
124
125 pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
126 pasteAct->setShortcuts(QKeySequence::Paste);
127 pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
128 "selection"));
129 connect(pasteAct, &QAction::triggered, textEdit, &QTextEdit::paste);
130
131 aboutAct = new QAction(tr("&About"), this);
132 aboutAct->setStatusTip(tr("Show the application's About box"));
133 connect(aboutAct, &QAction::triggered, this, &MainWindow::about);
134
135 aboutQtAct = new QAction(tr("About &Qt"), this);
136 aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
138
139 cutAct->setEnabled(false);
140 copyAct->setEnabled(false);
142 cutAct, &QAction::setEnabled);
144 copyAct, &QAction::setEnabled);
145}
146
147void MainWindow::createMenus()
148{
149 fileMenu = menuBar()->addMenu(tr("&File"));
150 fileMenu->addAction(newAct);
151 fileMenu->addAction(openAct);
152 fileMenu->addAction(saveAct);
153 fileMenu->addAction(saveAsAct);
154 fileMenu->addSeparator();
155 fileMenu->addAction(exitAct);
156
157 editMenu = menuBar()->addMenu(tr("&Edit"));
158 editMenu->addAction(cutAct);
159 editMenu->addAction(copyAct);
160 editMenu->addAction(pasteAct);
161
163
164 helpMenu = menuBar()->addMenu(tr("&Help"));
165 helpMenu->addAction(aboutAct);
166 helpMenu->addAction(aboutQtAct);
167}
168
169void MainWindow::createToolBars()
170{
171 fileToolBar = addToolBar(tr("File"));
172 fileToolBar->addAction(newAct);
173 fileToolBar->addAction(openAct);
174 fileToolBar->addAction(saveAct);
175
176 editToolBar = addToolBar(tr("Edit"));
177 editToolBar->addAction(cutAct);
178 editToolBar->addAction(copyAct);
179 editToolBar->addAction(pasteAct);
180}
181
182void MainWindow::createStatusBar()
183{
184 statusBar()->showMessage(tr("Ready"));
185}
186
188{
189 QSettings settings("QtProject", "Application Example");
190 QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
191 QSize size = settings.value("size", QSize(400, 400)).toSize();
192 resize(size);
193 move(pos);
194}
195
197{
198 QSettings settings("QtProject", "Application Example");
199 settings.setValue("pos", pos());
200 settings.setValue("size", size());
201}
202
203bool MainWindow::maybeSave()
204{
205 if (textEdit->document()->isModified()) {
207 ret = QMessageBox::warning(this, tr("Application"),
208 tr("The document has been modified.\n"
209 "Do you want to save your changes?"),
211 if (ret == QMessageBox::Save)
212 return save();
213 else if (ret == QMessageBox::Cancel)
214 return false;
215 }
216 return true;
217}
218
219void MainWindow::loadFile(const QString &fileName)
220{
223 QMessageBox::warning(this, tr("Application"),
224 tr("Cannot read file %1:\n%2.")
225 .arg(fileName)
226 .arg(file.errorString()));
227 return;
228 }
229
231#ifndef QT_NO_CURSOR
233#endif
234 textEdit->setPlainText(in.readAll());
235#ifndef QT_NO_CURSOR
237#endif
238
239 setCurrentFile(fileName);
240 statusBar()->showMessage(tr("File loaded"), 2000);
241}
242
244{
247 QMessageBox::warning(this, tr("Application"),
248 tr("Cannot write file %1:\n%2.")
249 .arg(fileName)
250 .arg(file.errorString()));
251 return false;
252 }
253
255#ifndef QT_NO_CURSOR
257#endif
258 out << textEdit->toPlainText();
259#ifndef QT_NO_CURSOR
261#endif
262
263 setCurrentFile(fileName);
264 statusBar()->showMessage(tr("File saved"), 2000);
265 return true;
266}
267
268void MainWindow::setCurrentFile(const QString &fileName)
269{
270 curFile = fileName;
271 textEdit->document()->setModified(false);
272 setWindowModified(false);
273
274 QString shownName = curFile;
275 if (curFile.isEmpty())
276 shownName = "untitled.txt";
277 setWindowFilePath(shownName);
278}
279
280QString MainWindow::strippedName(const QString &fullFileName)
281{
282 return QFileInfo(fullFileName).fileName();
283}
void closeEvent(QCloseEvent *event) override
[21]
void readSettings()
[16]
void saveFile()
void writeSettings()
[16]
QAction * newAct
Definition whatsthis.cpp:11
The QAction class provides an abstraction for user commands that can be added to different user inter...
Definition qaction.h:30
void setStatusTip(const QString &statusTip)
Definition qaction.cpp:712
void triggered(bool checked=false)
This signal is emitted when an action is activated by the user; for example, when the user clicks a m...
void setEnabled(bool)
Definition qaction.cpp:927
static void aboutQt()
Displays a simple message box about Qt.
The QCloseEvent class contains parameters that describe a close event.
Definition qevent.h:562
static QString getSaveFileName(QWidget *parent=nullptr, const QString &caption=QString(), const QString &dir=QString(), const QString &filter=QString(), QString *selectedFilter=nullptr, Options options=Options())
This is a convenience static function that returns a file name selected by the user.
static QString getOpenFileName(QWidget *parent=nullptr, const QString &caption=QString(), const QString &dir=QString(), const QString &filter=QString(), QString *selectedFilter=nullptr, Options options=Options())
This is a convenience static function that returns an existing file selected by the user.
QString fileName() const
\inmodule QtCore
Definition qfile.h:93
QFILE_MAYBE_NODISCARD bool open(OpenMode flags) override
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition qfile.cpp:904
static void setOverrideCursor(const QCursor &)
Sets the application override cursor to cursor.
static void restoreOverrideCursor()
Undoes the last setOverrideCursor().
QString errorString() const
Returns a human-readable description of the last device error that occurred.
The QIcon class provides scalable icons in different modes and states.
Definition qicon.h:20
void setCentralWidget(QWidget *widget)
Sets the given widget to be the main window's central widget.
QAction * addMenu(QMenu *menu)
Appends menu to the menu bar.
Definition qmenubar.cpp:768
QAction * addSeparator()
Appends a separator to the menu.
Definition qmenubar.cpp:778
static StandardButton warning(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons=Ok, StandardButton defaultButton=NoButton)
static void about(QWidget *parent, const QString &title, const QString &text)
Displays a simple about box with title title and text text.
static QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
\threadsafe
Definition qobject.cpp:2960
The QPlainTextEdit class provides a widget that is used to edit and display plain text.
\inmodule QtCore\reentrant
Definition qpoint.h:25
\inmodule QtCore
Definition qsettings.h:30
void setValue(QAnyStringView key, const QVariant &value)
Sets the value of setting key to value.
QVariant value(QAnyStringView key, const QVariant &defaultValue) const
Returns the value for setting key.
\inmodule QtCore
Definition qsize.h:25
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
void setModified(bool m=true)
bool isModified() const
void paste()
Pastes the text from the clipboard into the text edit at the current cursor position.
void copyAvailable(bool b)
This signal is emitted when text is selected or de-selected in the text edit.
void copy()
Copies any selected text to the clipboard.
void setPlainText(const QString &text)
Changes the text of the text edit to the string text.
void clear()
Deletes all the text in the text edit.
QString toPlainText() const
QString QTextEdit::toPlainText() const.
QTextDocument * document
the underlying document of the text editor.
Definition qtextedit.h:51
void cut()
Copies the selected text to the clipboard and deletes it from the text edit.
\inmodule QtCore
QPoint toPoint() const
Returns the variant as a QPoint if the variant has userType() \l QMetaType::QPoint or \l QMetaType::Q...
QSize toSize() const
Returns the variant as a QSize if the variant has userType() \l QMetaType::QSize; otherwise returns a...
void setWindowFilePath(const QString &filePath)
Definition qwidget.cpp:6250
QSize size
the size of the widget excluding any window frame
Definition qwidget.h:113
QPoint pos
the position of the widget within its parent widget
Definition qwidget.h:111
bool close()
Closes this widget.
Definition qwidget.cpp:8562
void move(int x, int y)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qwidget.h:880
void setWindowModified(bool)
void resize(int w, int h)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qwidget.h:883
@ WaitCursor
#define qApp
return ret
GLenum GLuint GLintptr GLsizeiptr size
[1]
struct _cl_event * event
GLuint in
SSL_CTX int void * arg
#define tr(X)
QFile file
[0]
QSettings settings("MySoft", "Star Runner")
[0]
QTextStream out(stdout)
[7]
QMenuBar * menuBar
[0]
statusBar() -> addWidget(new MyReadWriteIndication)
[0]