Cleanup QtWidgets (tools) examples

Cleanup QtWidgets tools examples:
 - use member-init (clang-tidy)
 - fix includes/don't include QtWidgets globally
 - include own header first
 - use nullptr (clang-tidy)
 - avoid c-style casts
 - use QVector instead QList
 - use QItemDelegate instead QStyledItemDelegate

Change-Id: Ibe9440cdf711e5cc2138c054864edebe1fc95731
Reviewed-by: Paul Wicking <paul.wicking@qt.io>
This commit is contained in:
Christian Ehrlicher 2019-09-06 20:27:33 +02:00
parent 78437ef0d2
commit 3fede6cb54
60 changed files with 427 additions and 377 deletions

View File

@ -48,12 +48,21 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "mainwindow.h" #include "mainwindow.h"
#include "encodingdialog.h" #include "encodingdialog.h"
#include "previewform.h" #include "previewform.h"
#include <QAction>
#include <QApplication>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QMenuBar>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QRegularExpression>
#include <QTextCodec>
#include <QTextStream>
MainWindow::MainWindow() MainWindow::MainWindow()
{ {
textEdit = new QPlainTextEdit; textEdit = new QPlainTextEdit;
@ -146,14 +155,14 @@ void MainWindow::findCodecs()
QTextCodec *codec = QTextCodec::codecForMib(mib); QTextCodec *codec = QTextCodec::codecForMib(mib);
QString sortKey = codec->name().toUpper(); QString sortKey = codec->name().toUpper();
int rank; char rank;
if (sortKey.startsWith(QLatin1String("UTF-8"))) { if (sortKey.startsWith(QLatin1String("UTF-8"))) {
rank = 1; rank = 1;
} else if (sortKey.startsWith(QLatin1String("UTF-16"))) { } else if (sortKey.startsWith(QLatin1String("UTF-16"))) {
rank = 2; rank = 2;
} else if ((match = iso8859RegExp.match(sortKey)).hasMatch()) { } else if ((match = iso8859RegExp.match(sortKey)).hasMatch()) {
if (match.captured(1).size() == 1) if (match.capturedRef(1).size() == 1)
rank = 3; rank = 3;
else else
rank = 4; rank = 4;
@ -164,7 +173,8 @@ void MainWindow::findCodecs()
codecMap.insert(sortKey, codec); codecMap.insert(sortKey, codec);
} }
codecs = codecMap.values(); for (const auto &codec : qAsConst(codecMap))
codecs += codec;
} }
void MainWindow::createMenus() void MainWindow::createMenus()

View File

@ -51,7 +51,7 @@
#ifndef MAINWINDOW_H #ifndef MAINWINDOW_H
#define MAINWINDOW_H #define MAINWINDOW_H
#include <QList> #include <QVector>
#include <QMainWindow> #include <QMainWindow>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
@ -81,10 +81,10 @@ private:
void findCodecs(); void findCodecs();
void createMenus(); void createMenus();
QList<QAction *> saveAsActs; QVector<QAction *> saveAsActs;
QPlainTextEdit *textEdit; QPlainTextEdit *textEdit;
PreviewForm *previewForm; PreviewForm *previewForm;
QList<QTextCodec *> codecs; QVector<QTextCodec *> codecs;
EncodingDialog *m_encodingDialog = nullptr; EncodingDialog *m_encodingDialog = nullptr;
}; };

View File

@ -48,10 +48,19 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "previewform.h" #include "previewform.h"
#include <QApplication>
#include <QComboBox>
#include <QDesktopWidget>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QLabel>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QTextCodec>
#include <QTextStream>
// Helpers for creating hex dumps // Helpers for creating hex dumps
static void indent(QTextStream &str, int indent) static void indent(QTextStream &str, int indent)
{ {
@ -83,8 +92,7 @@ static void formatHex(QTextStream &str, const QByteArray &data)
static void formatPrintableCharacters(QTextStream &str, const QByteArray &data) static void formatPrintableCharacters(QTextStream &str, const QByteArray &data)
{ {
for (int i = 0, size = data.size(); i < size; ++i) { for (const char c : data) {
const char c = data.at(i);
switch (c) { switch (c) {
case '\0': case '\0':
str << "\\0"; str << "\\0";
@ -179,7 +187,7 @@ PreviewForm::PreviewForm(QWidget *parent)
resize(screenGeometry.width() * 2 / 5, screenGeometry.height() / 2); resize(screenGeometry.width() * 2 / 5, screenGeometry.height() / 2);
} }
void PreviewForm::setCodecList(const QList<QTextCodec *> &list) void PreviewForm::setCodecList(const QVector<QTextCodec *> &list)
{ {
encodingComboBox->clear(); encodingComboBox->clear();
for (const QTextCodec *codec : list) { for (const QTextCodec *codec : list) {
@ -226,10 +234,10 @@ void PreviewForm::updateTextEdit()
statusLabel->setText(message); statusLabel->setText(message);
statusLabel->setStyleSheet(QStringLiteral("background-color: \"red\";")); statusLabel->setStyleSheet(QStringLiteral("background-color: \"red\";"));
} else if (state.invalidChars) { } else if (state.invalidChars) {
statusLabel->setText(tr("%1: %n invalid characters", 0, state.invalidChars).arg(name)); statusLabel->setText(tr("%1: %n invalid characters", nullptr, state.invalidChars).arg(name));
statusLabel->setStyleSheet(QStringLiteral("background-color: \"yellow\";")); statusLabel->setStyleSheet(QStringLiteral("background-color: \"yellow\";"));
} else { } else {
statusLabel->setText(tr("%1: %n bytes converted", 0, encodedData.size()).arg(name)); statusLabel->setText(tr("%1: %n bytes converted", nullptr, encodedData.size()).arg(name));
statusLabel->setStyleSheet(QString()); statusLabel->setStyleSheet(QString());
} }
if (success) if (success)

View File

@ -52,7 +52,7 @@
#define PREVIEWFORM_H #define PREVIEWFORM_H
#include <QDialog> #include <QDialog>
#include <QList> #include <QVector>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
class QComboBox; class QComboBox;
@ -71,7 +71,7 @@ class PreviewForm : public QDialog
public: public:
explicit PreviewForm(QWidget *parent = nullptr); explicit PreviewForm(QWidget *parent = nullptr);
void setCodecList(const QList<QTextCodec *> &list); void setCodecList(const QVector<QTextCodec *> &list);
void setEncodedData(const QByteArray &data); void setEncodedData(const QByteArray &data);
QString decodedString() const { return decodedStr; } QString decodedString() const { return decodedStr; }

View File

@ -62,7 +62,7 @@
class FileSystemModel : public QFileSystemModel class FileSystemModel : public QFileSystemModel
{ {
public: public:
FileSystemModel(QObject *parent = 0); FileSystemModel(QObject *parent = nullptr);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
}; };
//! [0] //! [0]

View File

@ -48,13 +48,28 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "fsmodel.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "fsmodel.h"
#include <QAction>
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QCompleter>
#include <QGridLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMenuBar>
#include <QMessageBox>
#include <QSpinBox>
#include <QStandardItemModel>
#include <QStringListModel>
#include <QTreeView>
//! [0] //! [0]
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), completer(0), lineEdit(0) : QMainWindow(parent)
{ {
createMenu(); createMenu();
@ -64,8 +79,8 @@ MainWindow::MainWindow(QWidget *parent)
modelLabel->setText(tr("Model")); modelLabel->setText(tr("Model"));
modelCombo = new QComboBox; modelCombo = new QComboBox;
modelCombo->addItem(tr("QFileSytemModel")); modelCombo->addItem(tr("QFileSystemModel"));
modelCombo->addItem(tr("QFileSytemModel that shows full path")); modelCombo->addItem(tr("QFileSystemModel that shows full path"));
modelCombo->addItem(tr("Country list")); modelCombo->addItem(tr("Country list"));
modelCombo->addItem(tr("Word list")); modelCombo->addItem(tr("Word list"));
modelCombo->setCurrentIndex(0); modelCombo->setCurrentIndex(0);
@ -144,17 +159,17 @@ void MainWindow::createMenu()
connect(aboutAct, &QAction::triggered, this, &MainWindow::about); connect(aboutAct, &QAction::triggered, this, &MainWindow::about);
connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
QMenu* fileMenu = menuBar()->addMenu(tr("File")); QMenu *fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(exitAction); fileMenu->addAction(exitAction);
QMenu* helpMenu = menuBar()->addMenu(tr("About")); QMenu *helpMenu = menuBar()->addMenu(tr("About"));
helpMenu->addAction(aboutAct); helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct); helpMenu->addAction(aboutQtAct);
} }
//! [4] //! [4]
//! [5] //! [5]
QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) QAbstractItemModel *MainWindow::modelFromFile(const QString &fileName)
{ {
QFile file(fileName); QFile file(fileName);
if (!file.open(QFile::ReadOnly)) if (!file.open(QFile::ReadOnly))
@ -170,7 +185,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
while (!file.atEnd()) { while (!file.atEnd()) {
QByteArray line = file.readLine(); QByteArray line = file.readLine();
if (!line.isEmpty()) if (!line.isEmpty())
words << line.trimmed(); words << QString::fromUtf8(line.trimmed());
} }
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
@ -191,8 +206,8 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
for (int i = 0; i < words.count(); ++i) { for (int i = 0; i < words.count(); ++i) {
QModelIndex countryIdx = m->index(i, 0); QModelIndex countryIdx = m->index(i, 0);
QModelIndex symbolIdx = m->index(i, 1); QModelIndex symbolIdx = m->index(i, 1);
QString country = words[i].mid(0, words[i].length() - 2).trimmed(); QString country = words.at(i).mid(0, words[i].length() - 2).trimmed();
QString symbol = words[i].right(2); QString symbol = words.at(i).right(2);
m->setData(countryIdx, country); m->setData(countryIdx, country);
m->setData(symbolIdx, symbol); m->setData(symbolIdx, symbol);
} }
@ -233,7 +248,7 @@ void MainWindow::changeModel()
case 0: case 0:
{ // Unsorted QFileSystemModel { // Unsorted QFileSystemModel
QFileSystemModel *fsModel = new QFileSystemModel(completer); QFileSystemModel *fsModel = new QFileSystemModel(completer);
fsModel->setRootPath(""); fsModel->setRootPath(QString());
completer->setModel(fsModel); completer->setModel(fsModel);
contentsLabel->setText(tr("Enter file path")); contentsLabel->setText(tr("Enter file path"));
} }
@ -243,7 +258,7 @@ void MainWindow::changeModel()
{ // FileSystemModel that shows full paths { // FileSystemModel that shows full paths
FileSystemModel *fsModel = new FileSystemModel(completer); FileSystemModel *fsModel = new FileSystemModel(completer);
completer->setModel(fsModel); completer->setModel(fsModel);
fsModel->setRootPath(""); fsModel->setRootPath(QString());
contentsLabel->setText(tr("Enter file path")); contentsLabel->setText(tr("Enter file path"));
} }
break; break;

View File

@ -59,7 +59,6 @@ class QComboBox;
class QCompleter; class QCompleter;
class QLabel; class QLabel;
class QLineEdit; class QLineEdit;
class QProgressBar;
class QCheckBox; class QCheckBox;
class QSpinBox; class QSpinBox;
QT_END_NAMESPACE QT_END_NAMESPACE
@ -70,7 +69,7 @@ class MainWindow : public QMainWindow
Q_OBJECT Q_OBJECT
public: public:
MainWindow(QWidget *parent = 0); MainWindow(QWidget *parent = nullptr);
private slots: private slots:
void about(); void about();
@ -83,16 +82,16 @@ private slots:
//! [1] //! [1]
private: private:
void createMenu(); void createMenu();
QAbstractItemModel *modelFromFile(const QString& fileName); QAbstractItemModel *modelFromFile(const QString &fileName);
QComboBox *caseCombo; QComboBox *caseCombo = nullptr;
QComboBox *modeCombo; QComboBox *modeCombo = nullptr;
QComboBox *modelCombo; QComboBox *modelCombo = nullptr;
QSpinBox *maxVisibleSpinBox; QSpinBox *maxVisibleSpinBox = nullptr;
QCheckBox *wrapCheckBox; QCheckBox *wrapCheckBox = nullptr;
QCompleter *completer; QCompleter *completer = nullptr;
QLabel *contentsLabel; QLabel *contentsLabel = nullptr;
QLineEdit *lineEdit; QLineEdit *lineEdit = nullptr;
}; };
//! [1] //! [1]

View File

@ -48,13 +48,20 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "mainwindow.h" #include "mainwindow.h"
#include "textedit.h" #include "textedit.h"
#include <QAction>
#include <QApplication>
#include <QCompleter>
#include <QFile>
#include <QMenuBar>
#include <QMessageBox>
#include <QStringListModel>
//! [0] //! [0]
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), completer(0) : QMainWindow(parent)
{ {
createMenu(); createMenu();
@ -83,10 +90,10 @@ void MainWindow::createMenu()
connect(aboutAct, &QAction::triggered, this, &MainWindow::about); connect(aboutAct, &QAction::triggered, this, &MainWindow::about);
connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
QMenu* fileMenu = menuBar()->addMenu(tr("File")); QMenu *fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(exitAction); fileMenu->addAction(exitAction);
QMenu* helpMenu = menuBar()->addMenu(tr("About")); QMenu *helpMenu = menuBar()->addMenu(tr("About"));
helpMenu->addAction(aboutAct); helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct); helpMenu->addAction(aboutQtAct);
} }
@ -107,7 +114,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
while (!file.atEnd()) { while (!file.atEnd()) {
QByteArray line = file.readLine(); QByteArray line = file.readLine();
if (!line.isEmpty()) if (!line.isEmpty())
words << line.trimmed(); words << QString::fromUtf8(line.trimmed());
} }
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR

View File

@ -55,11 +55,7 @@
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
class QAbstractItemModel; class QAbstractItemModel;
class QComboBox;
class QCompleter; class QCompleter;
class QLabel;
class QLineEdit;
class QProgressBar;
QT_END_NAMESPACE QT_END_NAMESPACE
class TextEdit; class TextEdit;
@ -69,7 +65,7 @@ class MainWindow : public QMainWindow
Q_OBJECT Q_OBJECT
public: public:
MainWindow(QWidget *parent = 0); MainWindow(QWidget *parent = nullptr);
private slots: private slots:
void about(); void about();
@ -78,7 +74,7 @@ private:
void createMenu(); void createMenu();
QAbstractItemModel *modelFromFile(const QString& fileName); QAbstractItemModel *modelFromFile(const QString& fileName);
QCompleter *completer; QCompleter *completer = nullptr;
TextEdit *completingTextEdit; TextEdit *completingTextEdit;
}; };
//! [0] //! [0]

View File

@ -60,7 +60,7 @@
//! [0] //! [0]
TextEdit::TextEdit(QWidget *parent) TextEdit::TextEdit(QWidget *parent)
: QTextEdit(parent), c(0) : QTextEdit(parent)
{ {
setPlainText(tr("This TextEdit provides autocompletions for words that have more than" setPlainText(tr("This TextEdit provides autocompletions for words that have more than"
" 3 characters. You can trigger autocompletion using ") + " 3 characters. You can trigger autocompletion using ") +
@ -78,7 +78,7 @@ TextEdit::~TextEdit()
void TextEdit::setCompleter(QCompleter *completer) void TextEdit::setCompleter(QCompleter *completer)
{ {
if (c) if (c)
QObject::disconnect(c, 0, this, 0); c->disconnect(this);
c = completer; c = completer;
@ -101,7 +101,7 @@ QCompleter *TextEdit::completer() const
//! [3] //! [3]
//! [4] //! [4]
void TextEdit::insertCompletion(const QString& completion) void TextEdit::insertCompletion(const QString &completion)
{ {
if (c->widget() != this) if (c->widget() != this)
return; return;
@ -150,18 +150,19 @@ void TextEdit::keyPressEvent(QKeyEvent *e)
} }
} }
bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E const bool isShortcut = (e->modifiers().testFlag(Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
if (!c || !isShortcut) // do not process the shortcut when we have a completer if (!c || !isShortcut) // do not process the shortcut when we have a completer
QTextEdit::keyPressEvent(e); QTextEdit::keyPressEvent(e);
//! [7] //! [7]
//! [8] //! [8]
const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); const bool ctrlOrShift = e->modifiers().testFlag(Qt::ControlModifier) ||
e->modifiers().testFlag(Qt::ShiftModifier);
if (!c || (ctrlOrShift && e->text().isEmpty())) if (!c || (ctrlOrShift && e->text().isEmpty()))
return; return;
static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word
bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; const bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
QString completionPrefix = textUnderCursor(); QString completionPrefix = textUnderCursor();
if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3

View File

@ -63,7 +63,7 @@ class TextEdit : public QTextEdit
Q_OBJECT Q_OBJECT
public: public:
TextEdit(QWidget *parent = 0); TextEdit(QWidget *parent = nullptr);
~TextEdit(); ~TextEdit();
void setCompleter(QCompleter *c); void setCompleter(QCompleter *c);
@ -80,7 +80,7 @@ private:
QString textUnderCursor() const; QString textUnderCursor() const;
private: private:
QCompleter *c; QCompleter *c = nullptr;
}; };
//! [0] //! [0]

View File

@ -51,13 +51,14 @@
#ifndef ECHOINTERFACE_H #ifndef ECHOINTERFACE_H
#define ECHOINTERFACE_H #define ECHOINTERFACE_H
#include <QObject>
#include <QString> #include <QString>
//! [0] //! [0]
class EchoInterface class EchoInterface
{ {
public: public:
virtual ~EchoInterface() {} virtual ~EchoInterface() = default;
virtual QString echo(const QString &message) = 0; virtual QString echo(const QString &message) = 0;
}; };

View File

@ -48,10 +48,17 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "echowindow.h" #include "echowindow.h"
#include <QCoreApplication>
#include <QDir>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QPluginLoader>
#include <QPushButton>
//! [0] //! [0]
EchoWindow::EchoWindow() EchoWindow::EchoWindow()
{ {
@ -101,7 +108,7 @@ void EchoWindow::createGUI()
//! [3] //! [3]
bool EchoWindow::loadPlugin() bool EchoWindow::loadPlugin()
{ {
QDir pluginsDir(qApp->applicationDirPath()); QDir pluginsDir(QCoreApplication::applicationDirPath());
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp(); pluginsDir.cdUp();
@ -121,6 +128,7 @@ bool EchoWindow::loadPlugin()
echoInterface = qobject_cast<EchoInterface *>(plugin); echoInterface = qobject_cast<EchoInterface *>(plugin);
if (echoInterface) if (echoInterface)
return true; return true;
pluginLoader.unload();
} }
} }

View File

@ -48,7 +48,7 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets> #include <QApplication>
#include "echowindow.h" #include "echowindow.h"
#include "echointerface.h" #include "echointerface.h"

View File

@ -48,8 +48,6 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "echoplugin.h" #include "echoplugin.h"
//! [0] //! [0]

View File

@ -48,34 +48,39 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "languagechooser.h" #include "languagechooser.h"
#include "mainwindow.h" #include "mainwindow.h"
LanguageChooser::LanguageChooser(const QString& defaultLang, QWidget *parent) #include <QCoreApplication>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QGridLayout>
#include <QGroupBox>
#include <QPushButton>
#include <QTranslator>
LanguageChooser::LanguageChooser(const QString &defaultLang, QWidget *parent)
: QDialog(parent, Qt::WindowStaysOnTopHint) : QDialog(parent, Qt::WindowStaysOnTopHint)
{ {
groupBox = new QGroupBox("Languages"); groupBox = new QGroupBox("Languages");
QGridLayout *groupBoxLayout = new QGridLayout; QGridLayout *groupBoxLayout = new QGridLayout;
QStringList qmFiles = findQmFiles(); const QStringList qmFiles = findQmFiles();
for (int i = 0; i < qmFiles.size(); ++i) { for (int i = 0; i < qmFiles.size(); ++i) {
QCheckBox *checkBox = new QCheckBox(languageName(qmFiles[i])); const QString &qmlFile = qmFiles.at(i);
qmFileForCheckBoxMap.insert(checkBox, qmFiles[i]); QCheckBox *checkBox = new QCheckBox(languageName(qmlFile));
connect(checkBox, qmFileForCheckBoxMap.insert(checkBox, qmlFile);
QOverload<bool>::of(&QCheckBox::toggled), connect(checkBox, &QCheckBox::toggled,
this, this, &LanguageChooser::checkBoxToggled);
&LanguageChooser::checkBoxToggled); if (languageMatch(defaultLang, qmlFile))
if (languageMatch(defaultLang, qmFiles[i])) checkBox->setCheckState(Qt::Checked);
checkBox->setCheckState(Qt::Checked);
groupBoxLayout->addWidget(checkBox, i / 2, i % 2); groupBoxLayout->addWidget(checkBox, i / 2, i % 2);
} }
groupBox->setLayout(groupBoxLayout); groupBox->setLayout(groupBoxLayout);
buttonBox = new QDialogButtonBox; buttonBox = new QDialogButtonBox;
showAllButton = buttonBox->addButton("Show All", showAllButton = buttonBox->addButton("Show All",
QDialogButtonBox::ActionRole); QDialogButtonBox::ActionRole);
hideAllButton = buttonBox->addButton("Hide All", hideAllButton = buttonBox->addButton("Hide All",
@ -92,7 +97,7 @@ LanguageChooser::LanguageChooser(const QString& defaultLang, QWidget *parent)
setWindowTitle("I18N"); setWindowTitle("I18N");
} }
bool LanguageChooser::languageMatch(const QString& lang, const QString& qmFile) bool LanguageChooser::languageMatch(const QString &lang, const QString &qmFile)
{ {
//qmFile: i18n_xx.qm //qmFile: i18n_xx.qm
const QString prefix = "i18n_"; const QString prefix = "i18n_";
@ -110,21 +115,21 @@ bool LanguageChooser::eventFilter(QObject *object, QEvent *event)
checkBox->setChecked(false); checkBox->setChecked(false);
} }
} }
return QWidget::eventFilter(object, event); return QDialog::eventFilter(object, event);
} }
void LanguageChooser::closeEvent(QCloseEvent * /* event */) void LanguageChooser::closeEvent(QCloseEvent * /* event */)
{ {
qApp->quit(); QCoreApplication::quit();
} }
void LanguageChooser::checkBoxToggled() void LanguageChooser::checkBoxToggled()
{ {
QCheckBox *checkBox = qobject_cast<QCheckBox *>(sender()); QCheckBox *checkBox = qobject_cast<QCheckBox *>(sender());
MainWindow *window = mainWindowForCheckBoxMap[checkBox]; MainWindow *window = mainWindowForCheckBoxMap.value(checkBox);
if (!window) { if (!window) {
QTranslator translator; QTranslator translator;
translator.load(qmFileForCheckBoxMap[checkBox]); translator.load(qmFileForCheckBoxMap.value(checkBox));
qApp->installTranslator(&translator); qApp->installTranslator(&translator);
window = new MainWindow; window = new MainWindow;

View File

@ -52,7 +52,7 @@
#define LANGUAGECHOOSER_H #define LANGUAGECHOOSER_H
#include <QDialog> #include <QDialog>
#include <QMap> #include <QHash>
#include <QStringList> #include <QStringList>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
@ -68,7 +68,7 @@ class LanguageChooser : public QDialog
Q_OBJECT Q_OBJECT
public: public:
explicit LanguageChooser(const QString& defaultLang = QString(), QWidget *parent = 0); explicit LanguageChooser(const QString &defaultLang = QString(), QWidget *parent = nullptr);
protected: protected:
bool eventFilter(QObject *object, QEvent *event) override; bool eventFilter(QObject *object, QEvent *event) override;
@ -80,17 +80,17 @@ private slots:
void hideAll(); void hideAll();
private: private:
QStringList findQmFiles(); static QStringList findQmFiles();
QString languageName(const QString &qmFile); static QString languageName(const QString &qmFile);
QColor colorForLanguage(const QString &language); static QColor colorForLanguage(const QString &language);
static bool languageMatch(const QString& lang, const QString& qmFile); static bool languageMatch(const QString &lang, const QString &qmFile);
QGroupBox *groupBox; QGroupBox *groupBox;
QDialogButtonBox *buttonBox; QDialogButtonBox *buttonBox;
QAbstractButton *showAllButton; QAbstractButton *showAllButton;
QAbstractButton *hideAllButton; QAbstractButton *hideAllButton;
QMap<QCheckBox *, QString> qmFileForCheckBoxMap; QHash<QCheckBox *, QString> qmFileForCheckBoxMap;
QMap<QCheckBox *, MainWindow *> mainWindowForCheckBoxMap; QHash<QCheckBox *, MainWindow *> mainWindowForCheckBoxMap;
}; };
#endif #endif

View File

@ -48,18 +48,26 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "mainwindow.h" #include "mainwindow.h"
#include <QAction>
#include <QCoreApplication>
#include <QGroupBox>
#include <QListWidget>
#include <QMenuBar>
#include <QRadioButton>
#include <QStatusBar>
#include <QVBoxLayout>
static const char * const listEntries[] = { static const char * const listEntries[] = {
QT_TRANSLATE_NOOP("MainWindow", "First"), QT_TRANSLATE_NOOP("MainWindow", "First"),
QT_TRANSLATE_NOOP("MainWindow", "Second"), QT_TRANSLATE_NOOP("MainWindow", "Second"),
QT_TRANSLATE_NOOP("MainWindow", "Third"), QT_TRANSLATE_NOOP("MainWindow", "Third"),
0 nullptr
}; };
MainWindow::MainWindow() MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{ {
centralWidget = new QWidget; centralWidget = new QWidget;
setCentralWidget(centralWidget); setCentralWidget(centralWidget);
@ -67,8 +75,8 @@ MainWindow::MainWindow()
createGroupBox(); createGroupBox();
listWidget = new QListWidget; listWidget = new QListWidget;
for (int i = 0; listEntries[i]; ++i) for (const char *entry : listEntries)
listWidget->addItem(tr(listEntries[i])); listWidget->addItem(tr(entry));
QVBoxLayout *mainLayout = new QVBoxLayout; QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(groupBox); mainLayout->addWidget(groupBox);
@ -76,7 +84,7 @@ MainWindow::MainWindow()
centralWidget->setLayout(mainLayout); centralWidget->setLayout(mainLayout);
exitAction = new QAction(tr("E&xit"), this); exitAction = new QAction(tr("E&xit"), this);
connect(exitAction, &QAction::triggered, qApp, QApplication::quit); connect(exitAction, &QAction::triggered, qApp, QCoreApplication::quit);
fileMenu = menuBar()->addMenu(tr("&File")); fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->setPalette(QPalette(Qt::red)); fileMenu->setPalette(QPalette(Qt::red));

View File

@ -67,7 +67,7 @@ class MainWindow : public QMainWindow
Q_OBJECT Q_OBJECT
public: public:
MainWindow(); MainWindow(QWidget *parent = nullptr);
private: private:
void createGroupBox(); void createGroupBox();

View File

@ -49,8 +49,8 @@
****************************************************************************/ ****************************************************************************/
#include "interfaces.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "interfaces.h"
#include "paintarea.h" #include "paintarea.h"
#include "plugindialog.h" #include "plugindialog.h"
@ -67,9 +67,8 @@
#include <QScrollArea> #include <QScrollArea>
#include <QTimer> #include <QTimer>
MainWindow::MainWindow() : MainWindow::MainWindow() : paintArea(new PaintArea)
paintArea(new PaintArea), , scrollArea(new QScrollArea)
scrollArea(new QScrollArea)
{ {
scrollArea->setBackgroundRole(QPalette::Dark); scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(paintArea); scrollArea->setWidget(paintArea);
@ -136,7 +135,11 @@ void MainWindow::brushWidth()
void MainWindow::changeBrush() void MainWindow::changeBrush()
{ {
auto action = qobject_cast<QAction *>(sender()); auto action = qobject_cast<QAction *>(sender());
if (!action)
return;
auto iBrush = qobject_cast<BrushInterface *>(action->parent()); auto iBrush = qobject_cast<BrushInterface *>(action->parent());
if (!iBrush)
return;
const QString brush = action->text(); const QString brush = action->text();
paintArea->setBrush(iBrush, brush); paintArea->setBrush(iBrush, brush);
@ -147,7 +150,11 @@ void MainWindow::changeBrush()
void MainWindow::insertShape() void MainWindow::insertShape()
{ {
auto action = qobject_cast<QAction *>(sender()); auto action = qobject_cast<QAction *>(sender());
if (!action)
return;
auto iShape = qobject_cast<ShapeInterface *>(action->parent()); auto iShape = qobject_cast<ShapeInterface *>(action->parent());
if (!iShape)
return;
const QPainterPath path = iShape->generateShape(action->text(), this); const QPainterPath path = iShape->generateShape(action->text(), this);
if (!path.isEmpty()) if (!path.isEmpty())
@ -159,7 +166,11 @@ void MainWindow::insertShape()
void MainWindow::applyFilter() void MainWindow::applyFilter()
{ {
auto action = qobject_cast<QAction *>(sender()); auto action = qobject_cast<QAction *>(sender());
if (!action)
return;
auto iFilter = qobject_cast<FilterInterface *>(action->parent()); auto iFilter = qobject_cast<FilterInterface *>(action->parent());
if (!iFilter)
return;
const QImage image = iFilter->filterImage(action->text(), paintArea->image(), const QImage image = iFilter->filterImage(action->text(), paintArea->image(),
this); this);
@ -247,7 +258,7 @@ void MainWindow::loadPlugins()
populateMenus(plugin); populateMenus(plugin);
//! [4] //! [5] //! [4] //! [5]
pluginsDir = QDir(qApp->applicationDirPath()); pluginsDir = QDir(QCoreApplication::applicationDirPath());
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")

View File

@ -49,14 +49,13 @@
****************************************************************************/ ****************************************************************************/
#include "interfaces.h"
#include "paintarea.h" #include "paintarea.h"
#include "interfaces.h"
#include <QMouseEvent> #include <QMouseEvent>
#include <QPainter> #include <QPainter>
PaintArea::PaintArea(QWidget *parent) : PaintArea::PaintArea(QWidget *parent) : QWidget(parent)
QWidget(parent)
{ {
setAttribute(Qt::WA_StaticContents); setAttribute(Qt::WA_StaticContents);
setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_OpaquePaintEvent);

View File

@ -49,8 +49,8 @@
****************************************************************************/ ****************************************************************************/
#include "interfaces.h"
#include "plugindialog.h" #include "plugindialog.h"
#include "interfaces.h"
#include <QDir> #include <QDir>
#include <QGridLayout> #include <QGridLayout>

View File

@ -50,10 +50,10 @@
#include "basictoolsplugin.h" #include "basictoolsplugin.h"
#include <QInputDialog>
#include <QPainter>
#include <QRandomGenerator>
#include <QtMath> #include <QtMath>
#include <QtWidgets>
#include <stdlib.h>
//! [0] //! [0]
QStringList BasicToolsPlugin::brushes() const QStringList BasicToolsPlugin::brushes() const

View File

@ -54,12 +54,12 @@
//! [0] //! [0]
#include <interfaces.h> #include <interfaces.h>
#include <QRect>
#include <QObject>
#include <QtPlugin>
#include <QStringList>
#include <QPainterPath>
#include <QImage> #include <QImage>
#include <QObject>
#include <QPainterPath>
#include <QRect>
#include <QStringList>
#include <QtPlugin>
//! [1] //! [1]
class BasicToolsPlugin : public QObject, class BasicToolsPlugin : public QObject,

View File

@ -50,10 +50,7 @@
#include "extrafiltersplugin.h" #include "extrafiltersplugin.h"
#include <QtWidgets> #include <QInputDialog>
#include <math.h>
#include <stdlib.h>
QStringList ExtraFiltersPlugin::filters() const QStringList ExtraFiltersPlugin::filters() const
{ {

View File

@ -65,7 +65,7 @@ class RegExpDialog : public QDialog
Q_OBJECT Q_OBJECT
public: public:
RegExpDialog(QWidget *parent = 0); RegExpDialog(QWidget *parent = nullptr);
private slots: private slots:
void refresh(); void refresh();

View File

@ -70,7 +70,7 @@ class RegularExpressionDialog : public QDialog
Q_OBJECT Q_OBJECT
public: public:
RegularExpressionDialog(QWidget *parent = 0); RegularExpressionDialog(QWidget *parent = nullptr);
private: private:
void refresh(); void refresh();

View File

@ -48,10 +48,20 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "locationdialog.h" #include "locationdialog.h"
#include <QBoxLayout>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QPushButton>
#include <QGroupBox>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QTableWidget>
#include <QTableWidgetItem>
LocationDialog::LocationDialog(QWidget *parent) LocationDialog::LocationDialog(QWidget *parent)
: QDialog(parent) : QDialog(parent)
{ {
@ -91,8 +101,7 @@ LocationDialog::LocationDialog(QWidget *parent)
locationsGroupBox = new QGroupBox(tr("Setting Locations")); locationsGroupBox = new QGroupBox(tr("Setting Locations"));
QStringList labels; const QStringList labels{tr("Location"), tr("Access")};
labels << tr("Location") << tr("Access");
locationsTable = new QTableWidget; locationsTable = new QTableWidget;
locationsTable->setSelectionMode(QAbstractItemView::SingleSelection); locationsTable->setSelectionMode(QAbstractItemView::SingleSelection);

View File

@ -68,7 +68,7 @@ class LocationDialog : public QDialog
Q_OBJECT Q_OBJECT
public: public:
LocationDialog(QWidget *parent = 0); LocationDialog(QWidget *parent = nullptr);
QSettings::Format format() const; QSettings::Format format() const;
QSettings::Scope scope() const; QSettings::Scope scope() const;

View File

@ -48,15 +48,23 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "locationdialog.h" #include "locationdialog.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "settingstree.h" #include "settingstree.h"
MainWindow::MainWindow() #include <QAction>
: settingsTree(new SettingsTree) #include <QApplication>
, locationDialog(nullptr) #include <QDesktopWidget>
#include <QFileDialog>
#include <QInputDialog>
#include <QLineEdit>
#include <QMenuBar>
#include <QMessageBox>
#include <QStandardPaths>
#include <QStatusBar>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
, settingsTree(new SettingsTree)
{ {
setCentralWidget(settingsTree); setCentralWidget(settingsTree);

View File

@ -68,7 +68,7 @@ class MainWindow : public QMainWindow
public: public:
typedef QSharedPointer<QSettings> SettingsPtr; typedef QSharedPointer<QSettings> SettingsPtr;
MainWindow(); MainWindow(QWidget *parent = nullptr);
private slots: private slots:
void openSettings(); void openSettings();
@ -81,11 +81,11 @@ private:
void createActions(); void createActions();
void setSettingsObject(const SettingsPtr &settings); void setSettingsObject(const SettingsPtr &settings);
SettingsTree *settingsTree; SettingsTree *settingsTree = nullptr;
LocationDialog *locationDialog; LocationDialog *locationDialog = nullptr;
QAction *refreshAct; QAction *refreshAct = nullptr;
QAction *autoRefreshAct; QAction *autoRefreshAct = nullptr;
QAction *fallbacksAct; QAction *fallbacksAct = nullptr;
}; };
#endif #endif

View File

@ -48,20 +48,20 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "settingstree.h" #include "settingstree.h"
#include "variantdelegate.h" #include "variantdelegate.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QHeaderView>
#include <QSettings>
SettingsTree::SettingsTree(QWidget *parent) SettingsTree::SettingsTree(QWidget *parent)
: QTreeWidget(parent) : QTreeWidget(parent)
, autoRefresh(false)
{ {
setItemDelegate(new VariantDelegate(this)); setItemDelegate(new VariantDelegate(this));
QStringList labels; setHeaderLabels({tr("Setting"), tr("Type"), tr("Value")});
labels << tr("Setting") << tr("Type") << tr("Value");
setHeaderLabels(labels);
header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
header()->setSectionResizeMode(2, QHeaderView::Stretch); header()->setSectionResizeMode(2, QHeaderView::Stretch);
@ -77,10 +77,6 @@ SettingsTree::SettingsTree(QWidget *parent)
connect(&refreshTimer, &QTimer::timeout, this, &SettingsTree::maybeRefresh); connect(&refreshTimer, &QTimer::timeout, this, &SettingsTree::maybeRefresh);
} }
SettingsTree::~SettingsTree()
{
}
void SettingsTree::setSettingsObject(const SettingsPtr &newSettings) void SettingsTree::setSettingsObject(const SettingsPtr &newSettings)
{ {
settings = newSettings; settings = newSettings;
@ -137,7 +133,7 @@ void SettingsTree::refresh()
this, &SettingsTree::updateSetting); this, &SettingsTree::updateSetting);
settings->sync(); settings->sync();
updateChildItems(0); updateChildItems(nullptr);
connect(this, &QTreeWidget::itemChanged, connect(this, &QTreeWidget::itemChanged,
this, &SettingsTree::updateSetting); this, &SettingsTree::updateSetting);
@ -228,7 +224,7 @@ void SettingsTree::updateChildItems(QTreeWidgetItem *parent)
QTreeWidgetItem *SettingsTree::createItem(const QString &text, QTreeWidgetItem *SettingsTree::createItem(const QString &text,
QTreeWidgetItem *parent, int index) QTreeWidgetItem *parent, int index)
{ {
QTreeWidgetItem *after = 0; QTreeWidgetItem *after = nullptr;
if (index != 0) if (index != 0)
after = childAt(parent, index - 1); after = childAt(parent, index - 1);
@ -243,24 +239,18 @@ QTreeWidgetItem *SettingsTree::createItem(const QString &text,
return item; return item;
} }
QTreeWidgetItem *SettingsTree::childAt(QTreeWidgetItem *parent, int index) QTreeWidgetItem *SettingsTree::childAt(QTreeWidgetItem *parent, int index) const
{ {
if (parent) return (parent ? parent->child(index) : topLevelItem(index));
return parent->child(index);
else
return topLevelItem(index);
} }
int SettingsTree::childCount(QTreeWidgetItem *parent) int SettingsTree::childCount(QTreeWidgetItem *parent) const
{ {
if (parent) return (parent ? parent->childCount() : topLevelItemCount());
return parent->childCount();
else
return topLevelItemCount();
} }
int SettingsTree::findChild(QTreeWidgetItem *parent, const QString &text, int SettingsTree::findChild(QTreeWidgetItem *parent, const QString &text,
int startIndex) int startIndex) const
{ {
for (int i = startIndex; i < childCount(parent); ++i) { for (int i = startIndex; i < childCount(parent); ++i) {
if (childAt(parent, i)->text(0) == text) if (childAt(parent, i)->text(0) == text)

View File

@ -65,10 +65,9 @@ class SettingsTree : public QTreeWidget
Q_OBJECT Q_OBJECT
public: public:
typedef QSharedPointer<QSettings> SettingsPtr; using SettingsPtr = QSharedPointer<QSettings>;
SettingsTree(QWidget *parent = 0); SettingsTree(QWidget *parent = nullptr);
~SettingsTree();
void setSettingsObject(const SettingsPtr &settings); void setSettingsObject(const SettingsPtr &settings);
QSize sizeHint() const override; QSize sizeHint() const override;
@ -89,16 +88,16 @@ private:
void updateChildItems(QTreeWidgetItem *parent); void updateChildItems(QTreeWidgetItem *parent);
QTreeWidgetItem *createItem(const QString &text, QTreeWidgetItem *parent, QTreeWidgetItem *createItem(const QString &text, QTreeWidgetItem *parent,
int index); int index);
QTreeWidgetItem *childAt(QTreeWidgetItem *parent, int index); QTreeWidgetItem *childAt(QTreeWidgetItem *parent, int index) const;
int childCount(QTreeWidgetItem *parent); int childCount(QTreeWidgetItem *parent) const;
int findChild(QTreeWidgetItem *parent, const QString &text, int startIndex); int findChild(QTreeWidgetItem *parent, const QString &text, int startIndex) const;
void moveItemForward(QTreeWidgetItem *parent, int oldIndex, int newIndex); void moveItemForward(QTreeWidgetItem *parent, int oldIndex, int newIndex);
SettingsPtr settings; SettingsPtr settings;
QTimer refreshTimer; QTimer refreshTimer;
bool autoRefresh;
QIcon groupIcon; QIcon groupIcon;
QIcon keyIcon; QIcon keyIcon;
bool autoRefresh = false;
}; };
#endif #endif

View File

@ -48,12 +48,14 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "variantdelegate.h" #include "variantdelegate.h"
#include <QDateTime>
#include <QLineEdit>
#include <QRegularExpressionValidator>
VariantDelegate::VariantDelegate(QObject *parent) VariantDelegate::VariantDelegate(QObject *parent)
: QItemDelegate(parent) : QStyledItemDelegate(parent)
{ {
boolExp.setPattern("true|false"); boolExp.setPattern("true|false");
boolExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption); boolExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
@ -82,12 +84,12 @@ void VariantDelegate::paint(QPainter *painter,
if (!isSupportedType(value.type())) { if (!isSupportedType(value.type())) {
QStyleOptionViewItem myOption = option; QStyleOptionViewItem myOption = option;
myOption.state &= ~QStyle::State_Enabled; myOption.state &= ~QStyle::State_Enabled;
QItemDelegate::paint(painter, myOption, index); QStyledItemDelegate::paint(painter, myOption, index);
return; return;
} }
} }
QItemDelegate::paint(painter, option, index); QStyledItemDelegate::paint(painter, option, index);
} }
QWidget *VariantDelegate::createEditor(QWidget *parent, QWidget *VariantDelegate::createEditor(QWidget *parent,
@ -95,11 +97,11 @@ QWidget *VariantDelegate::createEditor(QWidget *parent,
const QModelIndex &index) const const QModelIndex &index) const
{ {
if (index.column() != 2) if (index.column() != 2)
return 0; return nullptr;
QVariant originalValue = index.model()->data(index, Qt::UserRole); QVariant originalValue = index.model()->data(index, Qt::UserRole);
if (!isSupportedType(originalValue.type())) if (!isSupportedType(originalValue.type()))
return 0; return nullptr;
QLineEdit *lineEdit = new QLineEdit(parent); QLineEdit *lineEdit = new QLineEdit(parent);
lineEdit->setFrame(false); lineEdit->setFrame(false);
@ -149,7 +151,7 @@ QWidget *VariantDelegate::createEditor(QWidget *parent,
regExp = unsignedIntegerExp; regExp = unsignedIntegerExp;
break; break;
default: default:
; break;
} }
if (regExp.isValid()) { if (regExp.isValid()) {

View File

@ -51,15 +51,15 @@
#ifndef VARIANTDELEGATE_H #ifndef VARIANTDELEGATE_H
#define VARIANTDELEGATE_H #define VARIANTDELEGATE_H
#include <QItemDelegate> #include <QStyledItemDelegate>
#include <QRegularExpression> #include <QRegularExpression>
class VariantDelegate : public QItemDelegate class VariantDelegate : public QStyledItemDelegate
{ {
Q_OBJECT Q_OBJECT
public: public:
VariantDelegate(QObject *parent = 0); VariantDelegate(QObject *parent = nullptr);
void paint(QPainter *painter, const QStyleOptionViewItem &option, void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override; const QModelIndex &index) const override;

View File

@ -48,8 +48,6 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "simplestyle.h" #include "simplestyle.h"
void SimpleStyle::polish(QPalette &palette) void SimpleStyle::polish(QPalette &palette)

View File

@ -53,16 +53,12 @@
#include <QProxyStyle> #include <QProxyStyle>
QT_BEGIN_NAMESPACE
class QPalette;
QT_END_NAMESPACE
class SimpleStyle : public QProxyStyle class SimpleStyle : public QProxyStyle
{ {
Q_OBJECT Q_OBJECT
public: public:
SimpleStyle() {}; SimpleStyle() = default;
void polish(QPalette &palette) override; void polish(QPalette &palette) override;
}; };

View File

@ -48,15 +48,13 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "simplestyleplugin.h" #include "simplestyleplugin.h"
#include "simplestyle.h" #include "simplestyle.h"
//! [0] //! [0]
QStringList SimpleStylePlugin::keys() const QStringList SimpleStylePlugin::keys() const
{ {
return QStringList() << "SimpleStyle"; return {"SimpleStyle"};
} }
//! [0] //! [0]
@ -65,6 +63,6 @@ QStyle *SimpleStylePlugin::create(const QString &key)
{ {
if (key.toLower() == "simplestyle") if (key.toLower() == "simplestyle")
return new SimpleStyle; return new SimpleStyle;
return 0; return nullptr;
} }
//! [1] //! [1]

View File

@ -53,11 +53,6 @@
#include <QStylePlugin> #include <QStylePlugin>
QT_BEGIN_NAMESPACE
class QStringList;
class QStyle;
QT_END_NAMESPACE
//! [0] //! [0]
class SimpleStylePlugin : public QStylePlugin class SimpleStylePlugin : public QStylePlugin
{ {
@ -65,7 +60,7 @@ class SimpleStylePlugin : public QStylePlugin
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QStyleFactoryInterface" FILE "simplestyle.json") Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QStyleFactoryInterface" FILE "simplestyle.json")
public: public:
SimpleStylePlugin() {} SimpleStylePlugin() = default;
QStringList keys() const; QStringList keys() const;
QStyle *create(const QString &key) override; QStyle *create(const QString &key) override;

View File

@ -48,7 +48,8 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets> #include <QApplication>
#include <QStyleFactory>
#include "stylewindow.h" #include "stylewindow.h"

View File

@ -48,7 +48,9 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets> #include <QGridLayout>
#include <QGroupBox>
#include <QPushButton>
#include "stylewindow.h" #include "stylewindow.h"

View File

@ -48,13 +48,28 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "treemodelcompleter.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "treemodelcompleter.h"
#include <QAbstractProxyModel>
#include <QAction>
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QFile>
#include <QGridLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMenuBar>
#include <QMessageBox>
#include <QStandardItemModel>
#include <QStringListModel>
#include <QTreeView>
//! [0] //! [0]
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), completer(0), lineEdit(0) : QMainWindow(parent)
{ {
createMenu(); createMenu();
@ -151,10 +166,10 @@ void MainWindow::createMenu()
connect(aboutAct, &QAction::triggered, this, &MainWindow::about); connect(aboutAct, &QAction::triggered, this, &MainWindow::about);
connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
QMenu* fileMenu = menuBar()->addMenu(tr("File")); QMenu *fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(exitAction); fileMenu->addAction(exitAction);
QMenu* helpMenu = menuBar()->addMenu(tr("About")); QMenu *helpMenu = menuBar()->addMenu(tr("About"));
helpMenu->addAction(aboutAct); helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct); helpMenu->addAction(aboutQtAct);
} }
@ -175,7 +190,7 @@ void MainWindow::changeMode(int index)
} }
//! [5] //! [5]
QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) QAbstractItemModel *MainWindow::modelFromFile(const QString &fileName)
{ {
QFile file(fileName); QFile file(fileName);
if (!file.open(QFile::ReadOnly)) if (!file.open(QFile::ReadOnly))
@ -184,39 +199,35 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName)
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif #endif
QStringList words;
QStandardItemModel *model = new QStandardItemModel(completer); QStandardItemModel *model = new QStandardItemModel(completer);
QVector<QStandardItem *> parents(10); QVector<QStandardItem *> parents(10);
parents[0] = model->invisibleRootItem(); parents[0] = model->invisibleRootItem();
QRegularExpression re("^\\s+");
while (!file.atEnd()) { while (!file.atEnd()) {
QString line = file.readLine(); const QString line = QString::fromUtf8(file.readLine()).trimmed();
QString trimmedLine = line.trimmed(); const QString trimmedLine = line.trimmed();
if (line.isEmpty() || trimmedLine.isEmpty()) if (trimmedLine.isEmpty())
continue; continue;
QRegularExpression re("^\\s+"); const QRegularExpressionMatch match = re.match(line);
QRegularExpressionMatch match = re.match(line);
int nonws = match.capturedStart(); int nonws = match.capturedStart();
int level = 0; int level = 0;
if (nonws == -1) { if (nonws == -1) {
level = 0; level = 0;
} else { } else {
if (line.startsWith("\t")) { const int capLen = match.capturedLength();
level = match.capturedLength(); level = line.startsWith(QLatin1Char('\t')) ? capLen / 4 : capLen;
} else {
level = match.capturedLength()/4;
}
} }
if (level+1 >= parents.size()) if (level + 1 >= parents.size())
parents.resize(parents.size()*2); parents.resize(parents.size() * 2);
QStandardItem *item = new QStandardItem; QStandardItem *item = new QStandardItem;
item->setText(trimmedLine); item->setText(trimmedLine);
parents[level]->appendRow(item); parents[level]->appendRow(item);
parents[level+1] = item; parents[level + 1] = item;
} }
#ifndef QT_NO_CURSOR #ifndef QT_NO_CURSOR
@ -252,7 +263,7 @@ void MainWindow::changeCase(int cs)
} }
//! [7] //! [7]
void MainWindow::updateContentsLabel(const QString& sep) void MainWindow::updateContentsLabel(const QString &sep)
{ {
contentsLabel->setText(tr("Type path from model above with items at each level separated by a '%1'").arg(sep)); contentsLabel->setText(tr("Type path from model above with items at each level separated by a '%1'").arg(sep));
} }

View File

@ -60,8 +60,6 @@ class QAbstractItemModel;
class QComboBox; class QComboBox;
class QLabel; class QLabel;
class QLineEdit; class QLineEdit;
class QProgressBar;
class QCheckBox;
class QTreeView; class QTreeView;
QT_END_NAMESPACE QT_END_NAMESPACE
@ -71,27 +69,27 @@ class MainWindow : public QMainWindow
Q_OBJECT Q_OBJECT
public: public:
MainWindow(QWidget *parent = 0); MainWindow(QWidget *parent = nullptr);
private slots: private slots:
void about(); void about();
void changeCase(int); void changeCase(int);
void changeMode(int); void changeMode(int);
void highlight(const QModelIndex&); void highlight(const QModelIndex &index);
void updateContentsLabel(const QString&); void updateContentsLabel(const QString &sep);
//! [0] //! [0]
//! [1] //! [1]
private: private:
void createMenu(); void createMenu();
QAbstractItemModel *modelFromFile(const QString& fileName); QAbstractItemModel *modelFromFile(const QString &fileName);
QTreeView *treeView; QTreeView *treeView = nullptr;
QComboBox *caseCombo; QComboBox *caseCombo = nullptr;
QComboBox *modeCombo; QComboBox *modeCombo = nullptr;
QLabel *contentsLabel; QLabel *contentsLabel = nullptr;
TreeModelCompleter *completer; TreeModelCompleter *completer = nullptr;
QLineEdit *lineEdit; QLineEdit *lineEdit = nullptr;
}; };
//! [1] //! [1]

View File

@ -80,26 +80,20 @@ QString TreeModelCompleter::separator() const
//! [3] //! [3]
QStringList TreeModelCompleter::splitPath(const QString &path) const QStringList TreeModelCompleter::splitPath(const QString &path) const
{ {
if (sep.isNull()) { return (sep.isNull() ? QCompleter::splitPath(path) : path.split(sep));
return QCompleter::splitPath(path);
}
return path.split(sep);
} }
//! [3] //! [3]
//! [4] //! [4]
QString TreeModelCompleter::pathFromIndex(const QModelIndex &index) const QString TreeModelCompleter::pathFromIndex(const QModelIndex &index) const
{ {
if (sep.isNull()) { if (sep.isNull())
return QCompleter::pathFromIndex(index); return QCompleter::pathFromIndex(index);
}
// navigate up and accumulate data // navigate up and accumulate data
QStringList dataList; QStringList dataList;
for (QModelIndex i = index; i.isValid(); i = i.parent()) { for (QModelIndex i = index; i.isValid(); i = i.parent())
dataList.prepend(model()->data(i, completionRole()).toString()); dataList.prepend(model()->data(i, completionRole()).toString());
}
return dataList.join(sep); return dataList.join(sep);
} }

View File

@ -60,8 +60,8 @@ class TreeModelCompleter : public QCompleter
Q_PROPERTY(QString separator READ separator WRITE setSeparator) Q_PROPERTY(QString separator READ separator WRITE setSeparator)
public: public:
explicit TreeModelCompleter(QObject *parent = 0); explicit TreeModelCompleter(QObject *parent = nullptr);
explicit TreeModelCompleter(QAbstractItemModel *model, QObject *parent = 0); explicit TreeModelCompleter(QAbstractItemModel *model, QObject *parent = nullptr);
QString separator() const; QString separator() const;
public slots: public slots:

View File

@ -50,18 +50,16 @@
#include "commands.h" #include "commands.h"
static const int setShapeRectCommandId = 1; static constexpr int setShapeRectCommandId = 1;
static const int setShapeColorCommandId = 2; static constexpr int setShapeColorCommandId = 2;
/****************************************************************************** /******************************************************************************
** AddShapeCommand ** AddShapeCommand
*/ */
AddShapeCommand::AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent) AddShapeCommand::AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), m_doc(doc), m_shape(shape)
{ {
m_doc = doc;
m_shape = shape;
} }
void AddShapeCommand::undo() void AddShapeCommand::undo()
@ -81,13 +79,11 @@ void AddShapeCommand::redo()
*/ */
RemoveShapeCommand::RemoveShapeCommand(Document *doc, const QString &shapeName, RemoveShapeCommand::RemoveShapeCommand(Document *doc, const QString &shapeName,
QUndoCommand *parent) QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), m_doc(doc), m_shape(doc->shape(shapeName))
, m_shapeName(shapeName)
{ {
setText(QObject::tr("Remove %1").arg(shapeName)); setText(QObject::tr("Remove %1").arg(shapeName));
m_doc = doc;
m_shape = doc->shape(shapeName);
m_shapeName = shapeName;
} }
void RemoveShapeCommand::undo() void RemoveShapeCommand::undo()
@ -105,15 +101,11 @@ void RemoveShapeCommand::redo()
*/ */
SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName, SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName,
const QColor &color, QUndoCommand *parent) const QColor &color, QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), m_doc(doc), m_shapeName(shapeName)
, m_oldColor(doc->shape(shapeName).color()), m_newColor(color)
{ {
setText(QObject::tr("Set %1's color").arg(shapeName)); setText(QObject::tr("Set %1's color").arg(shapeName));
m_doc = doc;
m_shapeName = shapeName;
m_oldColor = doc->shape(shapeName).color();
m_newColor = color;
} }
void SetShapeColorCommand::undo() void SetShapeColorCommand::undo()
@ -149,15 +141,11 @@ int SetShapeColorCommand::id() const
*/ */
SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName, SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName,
const QRect &rect, QUndoCommand *parent) const QRect &rect, QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), m_doc(doc), m_shapeName(shapeName)
, m_oldRect(doc->shape(shapeName).rect()), m_newRect(rect)
{ {
setText(QObject::tr("Change %1's geometry").arg(shapeName)); setText(QObject::tr("Change %1's geometry").arg(shapeName));
m_doc = doc;
m_shapeName = shapeName;
m_oldRect = doc->shape(shapeName).rect();
m_newRect = rect;
} }
void SetShapeRectCommand::undo() void SetShapeRectCommand::undo()

View File

@ -57,7 +57,8 @@
class AddShapeCommand : public QUndoCommand class AddShapeCommand : public QUndoCommand
{ {
public: public:
AddShapeCommand(Document *doc, const Shape &shape, QUndoCommand *parent = 0); AddShapeCommand(Document *doc, const Shape &shape,
QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;
@ -70,7 +71,8 @@ private:
class RemoveShapeCommand : public QUndoCommand class RemoveShapeCommand : public QUndoCommand
{ {
public: public:
RemoveShapeCommand(Document *doc, const QString &shapeName, QUndoCommand *parent = 0); RemoveShapeCommand(Document *doc, const QString &shapeName,
QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;
@ -83,8 +85,8 @@ private:
class SetShapeColorCommand : public QUndoCommand class SetShapeColorCommand : public QUndoCommand
{ {
public: public:
SetShapeColorCommand(Document *doc, const QString &shapeName, const QColor &color, SetShapeColorCommand(Document *doc, const QString &shapeName,
QUndoCommand *parent = 0); const QColor &color, QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;
@ -102,8 +104,8 @@ private:
class SetShapeRectCommand : public QUndoCommand class SetShapeRectCommand : public QUndoCommand
{ {
public: public:
SetShapeRectCommand(Document *doc, const QString &shapeName, const QRect &rect, SetShapeRectCommand(Document *doc, const QString &shapeName,
QUndoCommand *parent = 0); const QRect &rect, QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;

View File

@ -48,14 +48,15 @@
** **
****************************************************************************/ ****************************************************************************/
#include <qevent.h>
#include <QPainter>
#include <QTextStream>
#include <QUndoStack>
#include "document.h" #include "document.h"
#include "commands.h" #include "commands.h"
static const int resizeHandleWidth = 6; #include <QPainter>
#include <QPaintEvent>
#include <QTextStream>
#include <QUndoStack>
static constexpr int resizeHandleWidth = 6;
/****************************************************************************** /******************************************************************************
** Shape ** Shape
@ -96,26 +97,21 @@ QRect Shape::resizeHandle() const
QString Shape::typeToString(Type type) QString Shape::typeToString(Type type)
{ {
QString result;
switch (type) { switch (type) {
case Rectangle: case Rectangle:
result = QLatin1String("Rectangle"); return QLatin1String("Rectangle");
break;
case Circle: case Circle:
result = QLatin1String("Circle"); return QLatin1String("Circle");
break;
case Triangle: case Triangle:
result = QLatin1String("Triangle"); return QLatin1String("Triangle");
break;
} }
return result; return QString();
} }
Shape::Type Shape::stringToType(const QString &s, bool *ok) Shape::Type Shape::stringToType(const QString &s, bool *ok)
{ {
if (ok != 0) if (ok != nullptr)
*ok = true; *ok = true;
if (s == QLatin1String("Rectangle")) if (s == QLatin1String("Rectangle"))
@ -125,7 +121,7 @@ Shape::Type Shape::stringToType(const QString &s, bool *ok)
if (s == QLatin1String("Triangle")) if (s == QLatin1String("Triangle"))
return Triangle; return Triangle;
if (ok != 0) if (ok != nullptr)
*ok = false; *ok = false;
return Rectangle; return Rectangle;
} }
@ -135,10 +131,8 @@ Shape::Type Shape::stringToType(const QString &s, bool *ok)
*/ */
Document::Document(QWidget *parent) Document::Document(QWidget *parent)
: QWidget(parent), m_currentIndex(-1), m_mousePressIndex(-1), m_resizeHandlePressed(false) : QWidget(parent), m_undoStack(new QUndoStack(this))
{ {
m_undoStack = new QUndoStack(this);
setAutoFillBackground(true); setAutoFillBackground(true);
setBackgroundRole(QPalette::Base); setBackgroundRole(QPalette::Base);

View File

@ -70,7 +70,7 @@ public:
QColor color() const; QColor color() const;
static QString typeToString(Type type); static QString typeToString(Type type);
static Type stringToType(const QString &s, bool *ok = 0); static Type stringToType(const QString &s, bool *ok = nullptr);
static const QSize minSize; static const QSize minSize;
@ -88,7 +88,7 @@ class Document : public QWidget
Q_OBJECT Q_OBJECT
public: public:
Document(QWidget *parent = 0); Document(QWidget *parent = nullptr);
QString addShape(const Shape &shape); QString addShape(const Shape &shape);
void deleteShape(const QString &shapeName); void deleteShape(const QString &shapeName);
@ -121,14 +121,13 @@ private:
int indexAt(const QPoint &pos) const; int indexAt(const QPoint &pos) const;
QString uniqueName(const QString &name) const; QString uniqueName(const QString &name) const;
QList<Shape> m_shapeList; QVector<Shape> m_shapeList;
int m_currentIndex;
int m_mousePressIndex;
QPoint m_mousePressOffset; QPoint m_mousePressOffset;
bool m_resizeHandlePressed;
QString m_fileName; QString m_fileName;
QUndoStack *m_undoStack = nullptr;
QUndoStack *m_undoStack; int m_currentIndex = -1;
int m_mousePressIndex = -1;
bool m_resizeHandlePressed = false;
}; };
#endif // DOCUMENT_H #endif // DOCUMENT_H

View File

@ -48,6 +48,10 @@
** **
****************************************************************************/ ****************************************************************************/
#include "mainwindow.h"
#include "document.h"
#include "commands.h"
#include <QUndoGroup> #include <QUndoGroup>
#include <QUndoStack> #include <QUndoStack>
#include <QFileDialog> #include <QFileDialog>
@ -55,9 +59,6 @@
#include <QRandomGenerator> #include <QRandomGenerator>
#include <QTextStream> #include <QTextStream>
#include <QToolButton> #include <QToolButton>
#include "document.h"
#include "mainwindow.h"
#include "commands.h"
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
@ -122,17 +123,17 @@ MainWindow::MainWindow(QWidget *parent)
void MainWindow::updateActions() void MainWindow::updateActions()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
m_undoGroup->setActiveStack(doc == 0 ? 0 : doc->undoStack()); m_undoGroup->setActiveStack(doc == nullptr ? nullptr : doc->undoStack());
QString shapeName = doc == 0 ? QString() : doc->currentShapeName(); QString shapeName = doc == nullptr ? QString() : doc->currentShapeName();
actionAddRobot->setEnabled(doc != 0); actionAddRobot->setEnabled(doc != nullptr);
actionAddSnowman->setEnabled(doc != 0); actionAddSnowman->setEnabled(doc != nullptr);
actionAddCircle->setEnabled(doc != 0); actionAddCircle->setEnabled(doc != nullptr);
actionAddRectangle->setEnabled(doc != 0); actionAddRectangle->setEnabled(doc != nullptr);
actionAddTriangle->setEnabled(doc != 0); actionAddTriangle->setEnabled(doc != nullptr);
actionClose->setEnabled(doc != 0); actionClose->setEnabled(doc != nullptr);
actionSave->setEnabled(doc != 0 && !doc->undoStack()->isClean()); actionSave->setEnabled(doc != nullptr && !doc->undoStack()->isClean());
undoLimit->setEnabled(doc != 0 && doc->undoStack()->count() == 0); undoLimit->setEnabled(doc != nullptr && doc->undoStack()->count() == 0);
if (shapeName.isEmpty()) { if (shapeName.isEmpty()) {
actionRed->setEnabled(false); actionRed->setEnabled(false);
@ -147,7 +148,7 @@ void MainWindow::updateActions()
actionRemoveShape->setEnabled(true); actionRemoveShape->setEnabled(true);
} }
if (doc != 0) { if (doc != nullptr) {
int index = documentTabs->indexOf(doc); int index = documentTabs->indexOf(doc);
Q_ASSERT(index != -1); Q_ASSERT(index != -1);
static const QIcon unsavedIcon(":/icons/filesave.png"); static const QIcon unsavedIcon(":/icons/filesave.png");
@ -264,7 +265,7 @@ void MainWindow::removeDocument(Document *doc)
void MainWindow::saveDocument() void MainWindow::saveDocument()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
for (;;) { for (;;) {
@ -298,7 +299,7 @@ void MainWindow::saveDocument()
void MainWindow::closeDocument() void MainWindow::closeDocument()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
if (!doc->undoStack()->isClean()) { if (!doc->undoStack()->isClean()) {
@ -338,10 +339,10 @@ static QRect randomRect(const QSize &s)
{ {
QSize min = Shape::minSize; QSize min = Shape::minSize;
int left = (int) ((0.0 + s.width() - min.width())*(QRandomGenerator::global()->bounded(1.0))); int left = qRound((s.width() - min.width()) * (QRandomGenerator::global()->bounded(1.0)));
int top = (int) ((0.0 + s.height() - min.height())*(QRandomGenerator::global()->bounded(1.0))); int top = qRound((s.height() - min.height()) * (QRandomGenerator::global()->bounded(1.0)));
int width = (int) ((0.0 + s.width() - left - min.width())*(QRandomGenerator::global()->bounded(1.0))) + min.width(); int width = qRound((s.width() - left - min.width()) * (QRandomGenerator::global()->bounded(1.0))) + min.width();
int height = (int) ((0.0 + s.height() - top - min.height())*(QRandomGenerator::global()->bounded(1.0))) + min.height(); int height = qRound((s.height() - top - min.height()) * (QRandomGenerator::global()->bounded(1.0))) + min.height();
return QRect(left, top, width, height); return QRect(left, top, width, height);
} }
@ -349,7 +350,7 @@ static QRect randomRect(const QSize &s)
void MainWindow::addShape() void MainWindow::addShape()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
Shape::Type type; Shape::Type type;
@ -369,7 +370,7 @@ void MainWindow::addShape()
void MainWindow::removeShape() void MainWindow::removeShape()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
QString shapeName = doc->currentShapeName(); QString shapeName = doc->currentShapeName();
@ -382,7 +383,7 @@ void MainWindow::removeShape()
void MainWindow::setShapeColor() void MainWindow::setShapeColor()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
QString shapeName = doc->currentShapeName(); QString shapeName = doc->currentShapeName();
@ -409,7 +410,7 @@ void MainWindow::setShapeColor()
void MainWindow::addSnowman() void MainWindow::addSnowman()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
// Create a macro command using beginMacro() and endMacro() // Create a macro command using beginMacro() and endMacro()
@ -427,7 +428,7 @@ void MainWindow::addSnowman()
void MainWindow::addRobot() void MainWindow::addRobot()
{ {
Document *doc = currentDocument(); Document *doc = currentDocument();
if (doc == 0) if (doc == nullptr)
return; return;
// Compose a macro command by explicitly adding children to a parent command // Compose a macro command by explicitly adding children to a parent command

View File

@ -61,7 +61,7 @@ class MainWindow : public QMainWindow, public Ui::MainWindow
Q_OBJECT Q_OBJECT
public: public:
MainWindow(QWidget *parent = 0); MainWindow(QWidget *parent = nullptr);
void addDocument(Document *doc); void addDocument(Document *doc);
void removeDocument(Document *doc); void removeDocument(Document *doc);

View File

@ -48,19 +48,17 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "commands.h" #include "commands.h"
#include "diagramitem.h" #include "diagramitem.h"
#include <QGraphicsScene>
//! [0] //! [0]
MoveCommand::MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, MoveCommand::MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos,
QUndoCommand *parent) QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), myDiagramItem(diagramItem)
, myOldPos(oldPos), newPos(diagramItem->pos())
{ {
myDiagramItem = diagramItem;
newPos = diagramItem->pos();
myOldPos = oldPos;
} }
//! [0] //! [0]
@ -71,7 +69,7 @@ bool MoveCommand::mergeWith(const QUndoCommand *command)
DiagramItem *item = moveCommand->myDiagramItem; DiagramItem *item = moveCommand->myDiagramItem;
if (myDiagramItem != item) if (myDiagramItem != item)
return false; return false;
newPos = item->pos(); newPos = item->pos();
setText(QObject::tr("Move %1") setText(QObject::tr("Move %1")
@ -102,9 +100,8 @@ void MoveCommand::redo()
//! [4] //! [4]
DeleteCommand::DeleteCommand(QGraphicsScene *scene, QUndoCommand *parent) DeleteCommand::DeleteCommand(QGraphicsScene *scene, QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), myGraphicsScene(scene)
{ {
myGraphicsScene = scene;
QList<QGraphicsItem *> list = myGraphicsScene->selectedItems(); QList<QGraphicsItem *> list = myGraphicsScene->selectedItems();
list.first()->setSelected(false); list.first()->setSelected(false);
myDiagramItem = static_cast<DiagramItem *>(list.first()); myDiagramItem = static_cast<DiagramItem *>(list.first());
@ -131,11 +128,10 @@ void DeleteCommand::redo()
//! [7] //! [7]
AddCommand::AddCommand(DiagramItem::DiagramType addType, AddCommand::AddCommand(DiagramItem::DiagramType addType,
QGraphicsScene *scene, QUndoCommand *parent) QGraphicsScene *scene, QUndoCommand *parent)
: QUndoCommand(parent) : QUndoCommand(parent), myGraphicsScene(scene)
{ {
static int itemCount = 0; static int itemCount = 0;
myGraphicsScene = scene;
myDiagramItem = new DiagramItem(addType); myDiagramItem = new DiagramItem(addType);
initialPosition = QPointF((itemCount * 15) % int(scene->width()), initialPosition = QPointF((itemCount * 15) % int(scene->width()),
(itemCount * 15) % int(scene->height())); (itemCount * 15) % int(scene->height()));

View File

@ -62,7 +62,7 @@ public:
enum { Id = 1234 }; enum { Id = 1234 };
MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos,
QUndoCommand *parent = 0); QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;
@ -80,7 +80,7 @@ private:
class DeleteCommand : public QUndoCommand class DeleteCommand : public QUndoCommand
{ {
public: public:
explicit DeleteCommand(QGraphicsScene *graphicsScene, QUndoCommand *parent = 0); explicit DeleteCommand(QGraphicsScene *graphicsScene, QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;
@ -96,7 +96,7 @@ class AddCommand : public QUndoCommand
{ {
public: public:
AddCommand(DiagramItem::DiagramType addType, QGraphicsScene *graphicsScene, AddCommand(DiagramItem::DiagramType addType, QGraphicsScene *graphicsScene,
QUndoCommand *parent = 0); QUndoCommand *parent = nullptr);
~AddCommand(); ~AddCommand();
void undo() override; void undo() override;

View File

@ -48,10 +48,11 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "diagramitem.h" #include "diagramitem.h"
#include <QBrush>
#include <QRandomGenerator>
DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item) DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item)
: QGraphicsPolygonItem(item) : QGraphicsPolygonItem(item)
{ {
@ -65,7 +66,9 @@ DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item)
setPolygon(trianglePolygon); setPolygon(trianglePolygon);
} }
QColor color(QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256), QRandomGenerator::global()->bounded(256)); QColor color(QRandomGenerator::global()->bounded(256),
QRandomGenerator::global()->bounded(256),
QRandomGenerator::global()->bounded(256));
QBrush brush(color); QBrush brush(color);
setBrush(brush); setBrush(brush);
setFlag(QGraphicsItem::ItemIsSelectable); setFlag(QGraphicsItem::ItemIsSelectable);

View File

@ -66,9 +66,10 @@ public:
enum { Type = UserType + 1 }; enum { Type = UserType + 1 };
enum DiagramType { Box, Triangle }; enum DiagramType { Box, Triangle };
explicit DiagramItem(DiagramType diagramType, QGraphicsItem *item = 0); explicit DiagramItem(DiagramType diagramType, QGraphicsItem *item = nullptr);
DiagramType diagramType() const { DiagramType diagramType() const
{
return polygon() == boxPolygon ? Box : Triangle; return polygon() == boxPolygon ? Box : Triangle;
} }
int type() const override { return Type; } int type() const override { return Type; }

View File

@ -48,27 +48,24 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "diagramscene.h" #include "diagramscene.h"
#include "diagramitem.h" #include "diagramitem.h"
#include <QGraphicsSceneMouseEvent>
DiagramScene::DiagramScene(QObject *parent) DiagramScene::DiagramScene(QObject *parent)
: QGraphicsScene(parent) : QGraphicsScene(parent)
{ {}
movingItem = 0;
}
void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *event) void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
QPointF mousePos(event->buttonDownScenePos(Qt::LeftButton).x(), QPointF mousePos(event->buttonDownScenePos(Qt::LeftButton).x(),
event->buttonDownScenePos(Qt::LeftButton).y()); event->buttonDownScenePos(Qt::LeftButton).y());
const QList<QGraphicsItem *> itemList = items(mousePos); const QList<QGraphicsItem *> itemList = items(mousePos);
movingItem = itemList.isEmpty() ? 0 : itemList.first(); movingItem = itemList.isEmpty() ? nullptr : itemList.first();
if (movingItem != 0 && event->button() == Qt::LeftButton) { if (movingItem != nullptr && event->button() == Qt::LeftButton)
oldPos = movingItem->pos(); oldPos = movingItem->pos();
}
clearSelection(); clearSelection();
QGraphicsScene::mousePressEvent(event); QGraphicsScene::mousePressEvent(event);
@ -76,11 +73,11 @@ void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (movingItem != 0 && event->button() == Qt::LeftButton) { if (movingItem != nullptr && event->button() == Qt::LeftButton) {
if (oldPos != movingItem->pos()) if (oldPos != movingItem->pos())
emit itemMoved(qgraphicsitem_cast<DiagramItem *>(movingItem), emit itemMoved(qgraphicsitem_cast<DiagramItem *>(movingItem),
oldPos); oldPos);
movingItem = 0; movingItem = nullptr;
} }
QGraphicsScene::mouseReleaseEvent(event); QGraphicsScene::mouseReleaseEvent(event);
} }

View File

@ -66,7 +66,7 @@ class DiagramScene : public QGraphicsScene
Q_OBJECT Q_OBJECT
public: public:
DiagramScene(QObject *parent = 0); DiagramScene(QObject *parent = nullptr);
signals: signals:
void itemMoved(DiagramItem *movedItem, const QPointF &movedFromPosition); void itemMoved(DiagramItem *movedItem, const QPointF &movedFromPosition);
@ -76,7 +76,7 @@ protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
private: private:
QGraphicsItem *movingItem; QGraphicsItem *movingItem = nullptr;
QPointF oldPos; QPointF oldPos;
}; };
//! [0] //! [0]

View File

@ -48,7 +48,7 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets> #include <QApplication>
#include "mainwindow.h" #include "mainwindow.h"

View File

@ -48,13 +48,18 @@
** **
****************************************************************************/ ****************************************************************************/
#include <QtWidgets>
#include "mainwindow.h" #include "mainwindow.h"
#include "diagramscene.h" #include "diagramscene.h"
#include "diagramitem.h" #include "diagramitem.h"
#include "commands.h" #include "commands.h"
#include <QAction>
#include <QGraphicsView>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QUndoView>
//! [0] //! [0]
MainWindow::MainWindow() MainWindow::MainWindow()
{ {

View File

@ -87,22 +87,22 @@ private:
void createMenus(); void createMenus();
void createUndoView(); void createUndoView();
QAction *deleteAction; QAction *deleteAction = nullptr;
QAction *addBoxAction; QAction *addBoxAction = nullptr;
QAction *addTriangleAction; QAction *addTriangleAction = nullptr;
QAction *undoAction; QAction *undoAction = nullptr;
QAction *redoAction; QAction *redoAction = nullptr;
QAction *exitAction; QAction *exitAction = nullptr;
QAction *aboutAction; QAction *aboutAction = nullptr;
QMenu *fileMenu; QMenu *fileMenu = nullptr;
QMenu *editMenu; QMenu *editMenu = nullptr;
QMenu *itemMenu; QMenu *itemMenu = nullptr;
QMenu *helpMenu; QMenu *helpMenu = nullptr;
DiagramScene *diagramScene; DiagramScene *diagramScene = nullptr;
QUndoStack *undoStack; QUndoStack *undoStack = nullptr;
QUndoView *undoView; QUndoView *undoView = nullptr;
}; };
//! [0] //! [0]