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 "encodingdialog.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()
{
textEdit = new QPlainTextEdit;
@ -146,14 +155,14 @@ void MainWindow::findCodecs()
QTextCodec *codec = QTextCodec::codecForMib(mib);
QString sortKey = codec->name().toUpper();
int rank;
char rank;
if (sortKey.startsWith(QLatin1String("UTF-8"))) {
rank = 1;
} else if (sortKey.startsWith(QLatin1String("UTF-16"))) {
rank = 2;
} else if ((match = iso8859RegExp.match(sortKey)).hasMatch()) {
if (match.captured(1).size() == 1)
if (match.capturedRef(1).size() == 1)
rank = 3;
else
rank = 4;
@ -164,7 +173,8 @@ void MainWindow::findCodecs()
codecMap.insert(sortKey, codec);
}
codecs = codecMap.values();
for (const auto &codec : qAsConst(codecMap))
codecs += codec;
}
void MainWindow::createMenus()

View File

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

View File

@ -48,10 +48,19 @@
**
****************************************************************************/
#include <QtWidgets>
#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
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)
{
for (int i = 0, size = data.size(); i < size; ++i) {
const char c = data.at(i);
for (const char c : data) {
switch (c) {
case '\0':
str << "\\0";
@ -179,7 +187,7 @@ PreviewForm::PreviewForm(QWidget *parent)
resize(screenGeometry.width() * 2 / 5, screenGeometry.height() / 2);
}
void PreviewForm::setCodecList(const QList<QTextCodec *> &list)
void PreviewForm::setCodecList(const QVector<QTextCodec *> &list)
{
encodingComboBox->clear();
for (const QTextCodec *codec : list) {
@ -226,10 +234,10 @@ void PreviewForm::updateTextEdit()
statusLabel->setText(message);
statusLabel->setStyleSheet(QStringLiteral("background-color: \"red\";"));
} 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\";"));
} 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());
}
if (success)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -48,10 +48,20 @@
**
****************************************************************************/
#include <QtWidgets>
#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)
: QDialog(parent)
{
@ -91,8 +101,7 @@ LocationDialog::LocationDialog(QWidget *parent)
locationsGroupBox = new QGroupBox(tr("Setting Locations"));
QStringList labels;
labels << tr("Location") << tr("Access");
const QStringList labels{tr("Location"), tr("Access")};
locationsTable = new QTableWidget;
locationsTable->setSelectionMode(QAbstractItemView::SingleSelection);

View File

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

View File

@ -48,15 +48,23 @@
**
****************************************************************************/
#include <QtWidgets>
#include "locationdialog.h"
#include "mainwindow.h"
#include "settingstree.h"
MainWindow::MainWindow()
: settingsTree(new SettingsTree)
, locationDialog(nullptr)
#include <QAction>
#include <QApplication>
#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);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -80,26 +80,20 @@ QString TreeModelCompleter::separator() const
//! [3]
QStringList TreeModelCompleter::splitPath(const QString &path) const
{
if (sep.isNull()) {
return QCompleter::splitPath(path);
}
return path.split(sep);
return (sep.isNull() ? QCompleter::splitPath(path) : path.split(sep));
}
//! [3]
//! [4]
QString TreeModelCompleter::pathFromIndex(const QModelIndex &index) const
{
if (sep.isNull()) {
if (sep.isNull())
return QCompleter::pathFromIndex(index);
}
// navigate up and accumulate data
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());
}
return dataList.join(sep);
}

View File

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

View File

@ -50,18 +50,16 @@
#include "commands.h"
static const int setShapeRectCommandId = 1;
static const int setShapeColorCommandId = 2;
static constexpr int setShapeRectCommandId = 1;
static constexpr int setShapeColorCommandId = 2;
/******************************************************************************
** AddShapeCommand
*/
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()
@ -81,13 +79,11 @@ void AddShapeCommand::redo()
*/
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));
m_doc = doc;
m_shape = doc->shape(shapeName);
m_shapeName = shapeName;
}
void RemoveShapeCommand::undo()
@ -105,15 +101,11 @@ void RemoveShapeCommand::redo()
*/
SetShapeColorCommand::SetShapeColorCommand(Document *doc, const QString &shapeName,
const QColor &color, QUndoCommand *parent)
: QUndoCommand(parent)
const QColor &color, 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));
m_doc = doc;
m_shapeName = shapeName;
m_oldColor = doc->shape(shapeName).color();
m_newColor = color;
}
void SetShapeColorCommand::undo()
@ -149,15 +141,11 @@ int SetShapeColorCommand::id() const
*/
SetShapeRectCommand::SetShapeRectCommand(Document *doc, const QString &shapeName,
const QRect &rect, QUndoCommand *parent)
: QUndoCommand(parent)
const QRect &rect, 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));
m_doc = doc;
m_shapeName = shapeName;
m_oldRect = doc->shape(shapeName).rect();
m_newRect = rect;
}
void SetShapeRectCommand::undo()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -48,10 +48,11 @@
**
****************************************************************************/
#include <QtWidgets>
#include "diagramitem.h"
#include <QBrush>
#include <QRandomGenerator>
DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item)
: QGraphicsPolygonItem(item)
{
@ -65,7 +66,9 @@ DiagramItem::DiagramItem(DiagramType diagramType, QGraphicsItem *item)
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);
setBrush(brush);
setFlag(QGraphicsItem::ItemIsSelectable);

View File

@ -66,9 +66,10 @@ public:
enum { Type = UserType + 1 };
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;
}
int type() const override { return Type; }

View File

@ -48,27 +48,24 @@
**
****************************************************************************/
#include <QtWidgets>
#include "diagramscene.h"
#include "diagramitem.h"
#include <QGraphicsSceneMouseEvent>
DiagramScene::DiagramScene(QObject *parent)
: QGraphicsScene(parent)
{
movingItem = 0;
}
{}
void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QPointF mousePos(event->buttonDownScenePos(Qt::LeftButton).x(),
event->buttonDownScenePos(Qt::LeftButton).y());
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();
}
clearSelection();
QGraphicsScene::mousePressEvent(event);
@ -76,11 +73,11 @@ void DiagramScene::mousePressEvent(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())
emit itemMoved(qgraphicsitem_cast<DiagramItem *>(movingItem),
oldPos);
movingItem = 0;
movingItem = nullptr;
}
QGraphicsScene::mouseReleaseEvent(event);
}

View File

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

View File

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

View File

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

View File

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