From c593492d1678a2ec08f1bfffcb572459b3bc6c00 Mon Sep 17 00:00:00 2001 From: Liang Qi Date: Wed, 26 Sep 2018 15:39:35 +0200 Subject: Modernize the "animation" feature Change-Id: Ibc164b3df3cf87db569ef4813de458a9067b7f7d Reviewed-by: Edward Welbourne Reviewed-by: Oswald Buddenhagen --- examples/widgets/animation/sub-attaq/qanimationstate.cpp | 5 ----- examples/widgets/animation/sub-attaq/qanimationstate.h | 5 ----- examples/widgets/widgets.pro | 1 + 3 files changed, 1 insertion(+), 10 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/animation/sub-attaq/qanimationstate.cpp b/examples/widgets/animation/sub-attaq/qanimationstate.cpp index 82bfdbf4b9..ae24af6da3 100644 --- a/examples/widgets/animation/sub-attaq/qanimationstate.cpp +++ b/examples/widgets/animation/sub-attaq/qanimationstate.cpp @@ -80,9 +80,6 @@ machine.start(); \sa QState, {The Animation Framework} */ - -#ifndef QT_NO_ANIMATION - /*! Constructs a new state with the given \a parent state. */ @@ -155,5 +152,3 @@ bool QAnimationState::event(QEvent *e) } QT_END_NAMESPACE - -#endif diff --git a/examples/widgets/animation/sub-attaq/qanimationstate.h b/examples/widgets/animation/sub-attaq/qanimationstate.h index 06ab4dfbcf..063b119058 100644 --- a/examples/widgets/animation/sub-attaq/qanimationstate.h +++ b/examples/widgets/animation/sub-attaq/qanimationstate.h @@ -61,9 +61,6 @@ QT_BEGIN_NAMESPACE - -#ifndef QT_NO_ANIMATION - class QAbstractAnimation; class QAnimationState : public QState @@ -89,8 +86,6 @@ private: QAbstractAnimation *m_animation; }; -#endif - QT_END_NAMESPACE #endif // QANIMATIONSTATE_H diff --git a/examples/widgets/widgets.pro b/examples/widgets/widgets.pro index f9d863b69e..7e52125125 100644 --- a/examples/widgets/widgets.pro +++ b/examples/widgets/widgets.pro @@ -27,4 +27,5 @@ qtHaveModule(gui):qtConfig(opengl): \ contains(DEFINES, QT_NO_CURSOR): SUBDIRS -= mainwindows !qtConfig(draganddrop): SUBDIRS -= draganddrop +!qtConfig(animation): SUBDIRS -= animation mac:SUBDIRS += mac -- cgit v1.2.3 From 0ead3b7142e47b89059af689de4ede47075375be Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Wed, 11 Jul 2018 15:12:56 +0200 Subject: Move arthurwidget based examples to new QOpenGL classes Several of the examples were not even working besides using deprecated classes. Change-Id: I352e0629d490593edcc5868d2ec5a8ff222eaeab Reviewed-by: Laszlo Agocs --- examples/widgets/painting/affine/affine.pro | 4 - examples/widgets/painting/affine/xform.cpp | 8 +- .../widgets/painting/composition/composition.cpp | 129 +++++++-------------- .../widgets/painting/composition/composition.h | 18 +-- .../widgets/painting/composition/composition.pro | 4 - examples/widgets/painting/composition/main.cpp | 7 +- examples/widgets/painting/deform/deform.pro | 4 - examples/widgets/painting/deform/pathdeform.cpp | 24 ++-- examples/widgets/painting/gradients/gradients.cpp | 8 +- examples/widgets/painting/gradients/gradients.pro | 4 - .../widgets/painting/pathstroke/pathstroke.cpp | 16 +-- .../widgets/painting/pathstroke/pathstroke.pro | 4 - examples/widgets/painting/shared/arthurwidgets.cpp | 80 ++++++++----- examples/widgets/painting/shared/arthurwidgets.h | 46 ++------ .../widgets/painting/shared/fbopaintdevice.cpp | 113 ++++++++++++++++++ examples/widgets/painting/shared/fbopaintdevice.h | 91 +++++++++++++++ examples/widgets/painting/shared/hoverpoints.cpp | 19 +-- examples/widgets/painting/shared/shared.pri | 6 +- 18 files changed, 346 insertions(+), 239 deletions(-) create mode 100644 examples/widgets/painting/shared/fbopaintdevice.cpp create mode 100644 examples/widgets/painting/shared/fbopaintdevice.h (limited to 'examples/widgets') diff --git a/examples/widgets/painting/affine/affine.pro b/examples/widgets/painting/affine/affine.pro index 0ad869183c..0af18b82ca 100644 --- a/examples/widgets/painting/affine/affine.pro +++ b/examples/widgets/painting/affine/affine.pro @@ -1,10 +1,6 @@ SOURCES += main.cpp xform.cpp HEADERS += xform.h -qtHaveModule(opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} QT += widgets SHARED_FOLDER = ../shared diff --git a/examples/widgets/painting/affine/xform.cpp b/examples/widgets/painting/affine/xform.cpp index 20f6eb3c6d..dc01acf453 100644 --- a/examples/widgets/painting/affine/xform.cpp +++ b/examples/widgets/painting/affine/xform.cpp @@ -830,13 +830,11 @@ XFormWidget::XFormWidget(QWidget *parent) QPushButton *showSourceButton = new QPushButton(mainGroup); showSourceButton->setText(tr("Show Source")); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(mainGroup); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(true); enableOpenGLButton->setChecked(view->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); #endif QPushButton *whatsThisButton = new QPushButton(mainGroup); whatsThisButton->setText(tr("What's This?")); @@ -871,7 +869,7 @@ XFormWidget::XFormWidget(QWidget *parent) mainGroupLayout->addWidget(resetButton); mainGroupLayout->addWidget(animateButton); mainGroupLayout->addWidget(showSourceButton); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) mainGroupLayout->addWidget(enableOpenGLButton); #endif mainGroupLayout->addWidget(whatsThisButton); @@ -897,7 +895,7 @@ XFormWidget::XFormWidget(QWidget *parent) connect(view, &XFormView::descriptionEnabledChanged, view->hoverPoints(), &HoverPoints::setDisabled); connect(view, &XFormView::descriptionEnabledChanged, whatsThisButton, &QPushButton::setChecked); connect(showSourceButton, &QPushButton::clicked, view, &XFormView::showSource); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) connect(enableOpenGLButton, &QPushButton::clicked, view, &XFormView::enableOpenGL); #endif view->loadSourceFile(":res/affine/xform.cpp"); diff --git a/examples/widgets/painting/composition/composition.cpp b/examples/widgets/painting/composition/composition.cpp index 0b57d3c7d3..3bc31b1fce 100644 --- a/examples/widgets/painting/composition/composition.cpp +++ b/examples/widgets/painting/composition/composition.cpp @@ -57,6 +57,11 @@ #include #include +#if QT_CONFIG(opengl) +#include +#include +#endif + const int animationInterval = 15; // update every 16 ms = ~60FPS CompositionWidget::CompositionWidget(QWidget *parent) @@ -136,14 +141,11 @@ CompositionWidget::CompositionWidget(QWidget *parent) QPushButton *showSourceButton = new QPushButton(mainGroup); showSourceButton->setText(tr("Show Source")); -#if defined(USE_OPENGL) && !defined(QT_OPENGL_ES) +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(mainGroup); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(true); enableOpenGLButton->setChecked(view->usesOpenGL()); - - if (!QGLFormat::hasOpenGL() || !QGLPixelBuffer::hasOpenGLPbuffers()) - enableOpenGLButton->hide(); #endif QPushButton *whatsThisButton = new QPushButton(mainGroup); whatsThisButton->setText(tr("What's This?")); @@ -166,7 +168,7 @@ CompositionWidget::CompositionWidget(QWidget *parent) mainGroupLayout->addWidget(animateButton); mainGroupLayout->addWidget(whatsThisButton); mainGroupLayout->addWidget(showSourceButton); -#if defined(USE_OPENGL) && !defined(QT_OPENGL_ES) +#if QT_CONFIG(opengl) mainGroupLayout->addWidget(enableOpenGLButton); #endif @@ -210,7 +212,7 @@ CompositionWidget::CompositionWidget(QWidget *parent) connect(whatsThisButton, SIGNAL(clicked(bool)), view, SLOT(setDescriptionEnabled(bool))); connect(view, SIGNAL(descriptionEnabledChanged(bool)), whatsThisButton, SLOT(setChecked(bool))); connect(showSourceButton, SIGNAL(clicked()), view, SLOT(showSource())); -#if defined(USE_OPENGL) && !defined(QT_OPENGL_ES) +#if QT_CONFIG(opengl) connect(enableOpenGLButton, SIGNAL(clicked(bool)), view, SLOT(enableOpenGL(bool))); #endif connect(animateButton, SIGNAL(toggled(bool)), view, SLOT(setAnimationEnabled(bool))); @@ -258,8 +260,7 @@ CompositionRenderer::CompositionRenderer(QWidget *parent) m_circle_pos = QPoint(200, 100); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); -#ifdef USE_OPENGL - m_pbuffer = 0; +#if QT_CONFIG(opengl) m_pbuffer_size = 1024; #endif } @@ -350,8 +351,11 @@ void CompositionRenderer::drawSource(QPainter &p) void CompositionRenderer::paint(QPainter *painter) { -#if defined(USE_OPENGL) && !defined(QT_OPENGL_ES) - if (usesOpenGL()) { +#if QT_CONFIG(opengl) + if (usesOpenGL() && glWindow()->isValid()) { + + if (!m_blitter.isCreated()) + m_blitter.create(); int new_pbuf_size = m_pbuffer_size; if (size().width() > m_pbuffer_size || size().height() > m_pbuffer_size) @@ -360,95 +364,46 @@ void CompositionRenderer::paint(QPainter *painter) if (size().width() < m_pbuffer_size/2 && size().height() < m_pbuffer_size/2) new_pbuf_size /= 2; - if (!m_pbuffer || new_pbuf_size != m_pbuffer_size) { - if (m_pbuffer) { - m_pbuffer->deleteTexture(m_base_tex); - m_pbuffer->deleteTexture(m_compositing_tex); - delete m_pbuffer; - } - - m_pbuffer = new QGLPixelBuffer(QSize(new_pbuf_size, new_pbuf_size), QGLFormat::defaultFormat(), glWidget()); - m_pbuffer->makeCurrent(); - m_base_tex = m_pbuffer->generateDynamicTexture(); - m_compositing_tex = m_pbuffer->generateDynamicTexture(); + if (!m_fbo || new_pbuf_size != m_pbuffer_size) { + m_fbo.reset(new QFboPaintDevice(QSize(new_pbuf_size, new_pbuf_size), false, false)); m_pbuffer_size = new_pbuf_size; } if (size() != m_previous_size) { m_previous_size = size(); - QPainter p(m_pbuffer); - p.setCompositionMode(QPainter::CompositionMode_Source); - p.fillRect(QRect(0, 0, m_pbuffer->width(), m_pbuffer->height()), Qt::transparent); + QPainter p(m_fbo.data()); drawBase(p); p.end(); - m_pbuffer->updateDynamicTexture(m_base_tex); + m_base_tex = m_fbo->takeTexture(); } - qreal x_fraction = width()/float(m_pbuffer->width()); - qreal y_fraction = height()/float(m_pbuffer->height()); - + painter->beginNativePainting(); { - QPainter p(m_pbuffer); - p.setCompositionMode(QPainter::CompositionMode_Source); - p.fillRect(QRect(0, 0, m_pbuffer->width(), m_pbuffer->height()), Qt::transparent); - - p.save(); // Needed when using the GL1 engine - p.beginNativePainting(); // Needed when using the GL2 engine - - glBindTexture(GL_TEXTURE_2D, m_base_tex); - glEnable(GL_TEXTURE_2D); - glColor4f(1.,1.,1.,1.); - - glBegin(GL_QUADS); - { - glTexCoord2f(0, 1.0); - glVertex2f(0, 0); - - glTexCoord2f(x_fraction, 1.0); - glVertex2f(width(), 0); - - glTexCoord2f(x_fraction, 1.0-y_fraction); - glVertex2f(width(), height()); - - glTexCoord2f(0, 1.0-y_fraction); - glVertex2f(0, height()); - } - glEnd(); - - glDisable(GL_TEXTURE_2D); - - p.endNativePainting(); // Needed when using the GL2 engine - p.restore(); // Needed when using the GL1 engine - + QPainter p(m_fbo.data()); + p.beginNativePainting(); + m_blitter.bind(); + const QRect targetRect(QPoint(0, 0), m_fbo->size()); + const QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(targetRect, QRect(QPoint(0, 0), m_fbo->size())); + m_blitter.blit(m_base_tex, target, QOpenGLTextureBlitter::OriginBottomLeft); + m_blitter.release(); + p.endNativePainting(); drawSource(p); p.end(); - m_pbuffer->updateDynamicTexture(m_compositing_tex); - } - - painter->beginNativePainting(); // Needed when using the GL2 engine - glWidget()->makeCurrent(); // Needed when using the GL1 engine - glBindTexture(GL_TEXTURE_2D, m_compositing_tex); - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(1.,1.,1.,1.); - glBegin(GL_QUADS); - { - glTexCoord2f(0, 1.0); - glVertex2f(0, 0); - - glTexCoord2f(x_fraction, 1.0); - glVertex2f(width(), 0); - - glTexCoord2f(x_fraction, 1.0-y_fraction); - glVertex2f(width(), height()); - - glTexCoord2f(0, 1.0-y_fraction); - glVertex2f(0, height()); + m_compositing_tex = m_fbo->takeTexture(); } - glEnd(); - glDisable(GL_TEXTURE_2D); - painter->endNativePainting(); // Needed when using the GL2 engine + painter->endNativePainting(); + + painter->beginNativePainting(); + auto *funcs = QOpenGLContext::currentContext()->functions(); + funcs->glEnable(GL_BLEND); + funcs->glBlendEquation(GL_FUNC_ADD); + funcs->glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + m_blitter.bind(); + const QRect targetRect(QPoint(0, 0), m_fbo->size()); + const QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(targetRect, QRect(QPoint(0, 0), size())); + m_blitter.blit(m_compositing_tex, target, QOpenGLTextureBlitter::OriginBottomLeft); + m_blitter.release(); + painter->endNativePainting(); } else #endif { @@ -520,7 +475,7 @@ void CompositionRenderer::setCirclePos(const QPointF &pos) const QRect oldRect = rectangle_around(m_circle_pos).toAlignedRect(); m_circle_pos = pos; const QRect newRect = rectangle_around(m_circle_pos).toAlignedRect(); -#if defined(USE_OPENGL) && !defined(QT_OPENGL_ES) +#if QT_CONFIG(opengl) if (usesOpenGL()) { update(); return; diff --git a/examples/widgets/painting/composition/composition.h b/examples/widgets/painting/composition/composition.h index 49853f503b..19150e2024 100644 --- a/examples/widgets/painting/composition/composition.h +++ b/examples/widgets/painting/composition/composition.h @@ -53,6 +53,11 @@ #include "arthurwidgets.h" +#if QT_CONFIG(opengl) +#include "fbopaintdevice.h" +#include +#endif + #include #include @@ -61,10 +66,6 @@ class QPushButton; class QRadioButton; QT_END_NAMESPACE -#ifdef QT_OPENGL_SUPPORT -#include -#endif - class CompositionWidget : public QWidget { Q_OBJECT @@ -186,12 +187,13 @@ private: bool m_animation_enabled; int m_animationTimer; -#ifdef QT_OPENGL_SUPPORT - QGLPixelBuffer *m_pbuffer; - GLuint m_base_tex; - GLuint m_compositing_tex; +#if QT_CONFIG(opengl) + QScopedPointer m_fbo; int m_pbuffer_size; // width==height==size of pbuffer + uint m_base_tex; + uint m_compositing_tex; QSize m_previous_size; + QOpenGLTextureBlitter m_blitter; #endif }; diff --git a/examples/widgets/painting/composition/composition.pro b/examples/widgets/painting/composition/composition.pro index 5fdbe4a5a2..15d8c6e67b 100644 --- a/examples/widgets/painting/composition/composition.pro +++ b/examples/widgets/painting/composition/composition.pro @@ -6,10 +6,6 @@ SHARED_FOLDER = ../shared include($$SHARED_FOLDER/shared.pri) RESOURCES += composition.qrc -qtHaveModule(opengl):!qtConfig(dynamicgl) { - DEFINES += USE_OPENGL - QT += opengl -} QT += widgets # install diff --git a/examples/widgets/painting/composition/main.cpp b/examples/widgets/painting/composition/main.cpp index 1a5dfd3e5e..1f4ead7165 100644 --- a/examples/widgets/painting/composition/main.cpp +++ b/examples/widgets/painting/composition/main.cpp @@ -51,17 +51,12 @@ #include "composition.h" #include -#ifdef QT_OPENGL_SUPPORT -#include -#endif int main(int argc, char *argv[]) { - // Q_INIT_RESOURCE(deform); - QApplication app(argc, argv); - CompositionWidget compWidget(0); + CompositionWidget compWidget(nullptr); QStyle *arthurStyle = new ArthurStyle(); compWidget.setStyle(arthurStyle); diff --git a/examples/widgets/painting/deform/deform.pro b/examples/widgets/painting/deform/deform.pro index 6409aaed96..498ec57686 100644 --- a/examples/widgets/painting/deform/deform.pro +++ b/examples/widgets/painting/deform/deform.pro @@ -7,10 +7,6 @@ include($$SHARED_FOLDER/shared.pri) RESOURCES += deform.qrc -qtHaveModule(opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} QT += widgets # install diff --git a/examples/widgets/painting/deform/pathdeform.cpp b/examples/widgets/painting/deform/pathdeform.cpp index 805804716f..7c3fe45277 100644 --- a/examples/widgets/painting/deform/pathdeform.cpp +++ b/examples/widgets/painting/deform/pathdeform.cpp @@ -109,13 +109,11 @@ void PathDeformControls::layoutForDesktop() QPushButton *showSourceButton = new QPushButton(mainGroup); showSourceButton->setText(tr("Show Source")); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(mainGroup); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(true); enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); #endif QPushButton *whatsThisButton = new QPushButton(mainGroup); @@ -132,7 +130,7 @@ void PathDeformControls::layoutForDesktop() mainGroupLayout->addWidget(textGroup); mainGroupLayout->addWidget(animateButton); mainGroupLayout->addStretch(1); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) mainGroupLayout->addWidget(enableOpenGLButton); #endif mainGroupLayout->addWidget(showSourceButton); @@ -158,7 +156,7 @@ void PathDeformControls::layoutForDesktop() connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); #endif @@ -201,13 +199,11 @@ void PathDeformControls::layoutForSmallScreen() QPushButton *animateButton = new QPushButton(tr("Animated"), mainGroup); animateButton->setCheckable(true); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(mainGroup); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(mainGroup); enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); #endif QPushButton *quitButton = new QPushButton(tr("Quit"), mainGroup); @@ -223,7 +219,7 @@ void PathDeformControls::layoutForSmallScreen() mainGroupLayout->addWidget(fontSizeLabel, 2, 0, Qt::AlignRight); mainGroupLayout->addWidget(fontSizeSlider, 2, 1); mainGroupLayout->addWidget(animateButton, 3,0, 1,2); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) mainGroupLayout->addWidget(enableOpenGLButton, 4,0, 1,2); #endif @@ -239,7 +235,7 @@ void PathDeformControls::layoutForSmallScreen() connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); #endif @@ -463,7 +459,7 @@ void PathDeformRenderer::timerEvent(QTimerEvent *e) m_pos.setY(height() - m_radius); } -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) if (usesOpenGL()) { update(); } else @@ -527,7 +523,7 @@ void PathDeformRenderer::mouseMoveEvent(QMouseEvent *e) m_direction = (m_direction + dir) / 2; } m_pos = e->pos() + m_offset; -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) if (usesOpenGL()) { update(); } else @@ -620,7 +616,7 @@ void PathDeformRenderer::setRadius(int radius) m_radius = radius; generateLensPixmap(); if (!m_animated || m_radius < max) { -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) if (usesOpenGL()){ update(); return; @@ -634,7 +630,7 @@ void PathDeformRenderer::setIntensity(int intensity) { m_intensity = intensity; if (!m_animated) { -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) if (usesOpenGL()) { update(); return; diff --git a/examples/widgets/painting/gradients/gradients.cpp b/examples/widgets/painting/gradients/gradients.cpp index 6d9f514a8d..004f6710cd 100644 --- a/examples/widgets/painting/gradients/gradients.cpp +++ b/examples/widgets/painting/gradients/gradients.cpp @@ -317,13 +317,11 @@ GradientWidget::GradientWidget(QWidget *parent) QPushButton *showSourceButton = new QPushButton(mainGroup); showSourceButton->setText(tr("Show Source")); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(mainGroup); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(true); enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); #endif QPushButton *whatsThisButton = new QPushButton(mainGroup); whatsThisButton->setText(tr("What's This?")); @@ -343,7 +341,7 @@ GradientWidget::GradientWidget(QWidget *parent) mainGroupLayout->addWidget(defaultsGroup); mainGroupLayout->addStretch(1); mainGroupLayout->addWidget(showSourceButton); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) mainGroupLayout->addWidget(enableOpenGLButton); #endif mainGroupLayout->addWidget(whatsThisButton); @@ -406,7 +404,7 @@ GradientWidget::GradientWidget(QWidget *parent) connect(showSourceButton, &QPushButton::clicked, m_renderer, &GradientRenderer::showSource); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) connect(enableOpenGLButton, QOverload::of(&QPushButton::clicked), m_renderer, &ArthurFrame::enableOpenGL); #endif diff --git a/examples/widgets/painting/gradients/gradients.pro b/examples/widgets/painting/gradients/gradients.pro index 73f3974c62..14eccb6500 100644 --- a/examples/widgets/painting/gradients/gradients.pro +++ b/examples/widgets/painting/gradients/gradients.pro @@ -6,10 +6,6 @@ SHARED_FOLDER = ../shared include($$SHARED_FOLDER/shared.pri) RESOURCES += gradients.qrc -qtHaveModule(opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} QT += widgets # install diff --git a/examples/widgets/painting/pathstroke/pathstroke.cpp b/examples/widgets/painting/pathstroke/pathstroke.cpp index 5a7b8fd9fe..b04998afac 100644 --- a/examples/widgets/painting/pathstroke/pathstroke.cpp +++ b/examples/widgets/painting/pathstroke/pathstroke.cpp @@ -211,13 +211,11 @@ void PathStrokeControls::layoutForDesktop() QPushButton *showSourceButton = new QPushButton(mainGroup); showSourceButton->setText(tr("Show Source")); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(mainGroup); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(true); enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); #endif QPushButton *whatsThisButton = new QPushButton(mainGroup); whatsThisButton->setText(tr("What's This?")); @@ -242,7 +240,7 @@ void PathStrokeControls::layoutForDesktop() mainGroupLayout->addWidget(animated); mainGroupLayout->addStretch(1); mainGroupLayout->addWidget(showSourceButton); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) mainGroupLayout->addWidget(enableOpenGLButton); #endif mainGroupLayout->addWidget(whatsThisButton); @@ -254,7 +252,7 @@ void PathStrokeControls::layoutForDesktop() connect(penWidth, SIGNAL(valueChanged(int)), m_renderer, SLOT(setPenWidth(int))); connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); #endif connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); @@ -290,13 +288,11 @@ void PathStrokeControls::layoutForSmallScreens() penWidth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); penWidth->setRange(0, 500); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) QPushButton *enableOpenGLButton = new QPushButton(this); enableOpenGLButton->setText(tr("Use OpenGL")); enableOpenGLButton->setCheckable(true); enableOpenGLButton->setChecked(m_renderer->usesOpenGL()); - if (!QGLFormat::hasOpenGL()) - enableOpenGLButton->hide(); #endif // Layouts: @@ -307,7 +303,7 @@ void PathStrokeControls::layoutForSmallScreens() QVBoxLayout *leftLayout = new QVBoxLayout(0); leftLayout->addWidget(m_capGroup); leftLayout->addWidget(m_joinGroup); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) leftLayout->addWidget(enableOpenGLButton); #endif leftLayout->addLayout(penWidthLayout); @@ -330,7 +326,7 @@ void PathStrokeControls::layoutForSmallScreens() mainLayout->addWidget(quitBtn, 2, 1, Qt::AlignHCenter | Qt::AlignTop); mainLayout->addWidget(okBtn, 2, 2, Qt::AlignHCenter | Qt::AlignTop); -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); #endif diff --git a/examples/widgets/painting/pathstroke/pathstroke.pro b/examples/widgets/painting/pathstroke/pathstroke.pro index 8ab3cb9244..3e71b2db56 100644 --- a/examples/widgets/painting/pathstroke/pathstroke.pro +++ b/examples/widgets/painting/pathstroke/pathstroke.pro @@ -7,10 +7,6 @@ include($$SHARED_FOLDER/shared.pri) RESOURCES += pathstroke.qrc -qtHaveModule(opengl) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl -} QT += widgets # install diff --git a/examples/widgets/painting/shared/arthurwidgets.cpp b/examples/widgets/painting/shared/arthurwidgets.cpp index 965660a3a3..442fb69ac1 100644 --- a/examples/widgets/painting/shared/arthurwidgets.cpp +++ b/examples/widgets/painting/shared/arthurwidgets.cpp @@ -60,6 +60,10 @@ #include #include #include +#include +#include +#include +#include extern QPixmap cached(const QString &img); @@ -67,17 +71,12 @@ ArthurFrame::ArthurFrame(QWidget *parent) : QWidget(parent) , m_prefer_image(false) { -#ifdef QT_OPENGL_SUPPORT - glw = 0; +#if QT_CONFIG(opengl) + m_glWindow = nullptr; + m_glWidget = nullptr; m_use_opengl = false; - QGLFormat f = QGLFormat::defaultFormat(); - f.setSampleBuffers(true); - f.setStencil(true); - f.setAlpha(true); - f.setAlphaBufferSize(8); - QGLFormat::setDefaultFormat(f); #endif - m_document = 0; + m_document = nullptr; m_show_doc = false; m_tile = QPixmap(128, 128); @@ -94,37 +93,55 @@ ArthurFrame::ArthurFrame(QWidget *parent) } -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) void ArthurFrame::enableOpenGL(bool use_opengl) { if (m_use_opengl == use_opengl) return; - if (!glw && use_opengl) { - glw = new GLWidget(this); - glw->setAutoFillBackground(false); - glw->disableAutoBufferSwap(); + m_use_opengl = use_opengl; + + if (!m_glWindow && use_opengl) { + createGlWindow(); QApplication::postEvent(this, new QResizeEvent(size(), size())); } - m_use_opengl = use_opengl; if (use_opengl) { - glw->show(); + m_glWidget->show(); } else { - if (glw) - glw->hide(); + if (m_glWidget) + m_glWidget->hide(); } update(); } + +void ArthurFrame::createGlWindow() +{ + Q_ASSERT(m_use_opengl); + + m_glWindow = new QOpenGLWindow(); + QSurfaceFormat f = QSurfaceFormat::defaultFormat(); + f.setSamples(4); + f.setAlphaBufferSize(8); + f.setStencilBufferSize(8); + m_glWindow->setFormat(f); + m_glWindow->setFlags(Qt::WindowTransparentForInput); + m_glWindow->resize(width() - 1, height() - 1); + m_glWindow->create(); + m_glWidget = QWidget::createWindowContainer(m_glWindow, this); +} #endif + void ArthurFrame::paintEvent(QPaintEvent *e) { static QImage *static_image = 0; + QPainter painter; + if (preferImage() -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) && !m_use_opengl #endif ) { @@ -142,10 +159,12 @@ void ArthurFrame::paintEvent(QPaintEvent *e) painter.fillRect(0, height() - o, o, o, bg); painter.fillRect(width() - o, height() - o, o, o, bg); } else { -#ifdef QT_OPENGL_SUPPORT - if (m_use_opengl) { - painter.begin(glw); - painter.fillRect(QRectF(0, 0, glw->width(), glw->height()), palette().color(backgroundRole())); +#if QT_CONFIG(opengl) + if (m_use_opengl && m_glWindow->isValid()) { + m_glWindow->makeCurrent(); + + painter.begin(m_glWindow); + painter.fillRect(QRectF(0, 0, m_glWindow->width(), m_glWindow->height()), palette().color(backgroundRole())); } else { painter.begin(this); } @@ -196,7 +215,7 @@ void ArthurFrame::paintEvent(QPaintEvent *e) painter.drawPath(clipPath); if (preferImage() -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) && !m_use_opengl #endif ) { @@ -204,18 +223,17 @@ void ArthurFrame::paintEvent(QPaintEvent *e) painter.begin(this); painter.drawImage(e->rect(), *static_image, e->rect()); } - -#ifdef QT_OPENGL_SUPPORT - if (m_use_opengl && (inherits("PathDeformRenderer") || inherits("PathStrokeRenderer") || inherits("CompositionRenderer") || m_show_doc)) - glw->swapBuffers(); +#if QT_CONFIG(opengl) + if (m_use_opengl) + m_glWindow->update(); #endif } void ArthurFrame::resizeEvent(QResizeEvent *e) { -#ifdef QT_OPENGL_SUPPORT - if (glw) - glw->setGeometry(0, 0, e->size().width()-1, e->size().height()-1); +#if QT_CONFIG(opengl) + if (m_glWidget) + m_glWidget->setGeometry(0, 0, e->size().width()-1, e->size().height()-1); #endif QWidget::resizeEvent(e); } diff --git a/examples/widgets/painting/shared/arthurwidgets.h b/examples/widgets/painting/shared/arthurwidgets.h index d6e1e44b3a..73e1310c0e 100644 --- a/examples/widgets/painting/shared/arthurwidgets.h +++ b/examples/widgets/painting/shared/arthurwidgets.h @@ -56,42 +56,13 @@ #include #include -#if defined(QT_OPENGL_SUPPORT) -#include -#include -class GLWidget : public QGLWidget -{ -public: - GLWidget(QWidget *parent) - : QGLWidget(QGLFormat(QGL::SampleBuffers), parent) - { - setAttribute(Qt::WA_AcceptTouchEvents); - } - void disableAutoBufferSwap() { setAutoBufferSwap(false); } - void paintEvent(QPaintEvent *) override { parentWidget()->update(); } -protected: - bool event(QEvent *event) override - { - switch (event->type()) { - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - event->ignore(); - return false; - break; - default: - break; - } - return QGLWidget::event(event); - } -}; -#endif - +QT_FORWARD_DECLARE_CLASS(QOpenGLWindow) QT_FORWARD_DECLARE_CLASS(QTextDocument) QT_FORWARD_DECLARE_CLASS(QTextEdit) QT_FORWARD_DECLARE_CLASS(QVBoxLayout) class ArthurFrame : public QWidget + { Q_OBJECT public: @@ -107,9 +78,8 @@ public: void loadSourceFile(const QString &fileName); bool preferImage() const { return m_prefer_image; } - -#if defined(QT_OPENGL_SUPPORT) - QGLWidget *glWidget() const { return glw; } +#if QT_CONFIG(opengl) + QOpenGLWindow *glWindow() const { return m_glWindow; } #endif public slots: @@ -117,7 +87,7 @@ public slots: void setDescriptionEnabled(bool enabled); void showSource(); -#if defined(QT_OPENGL_SUPPORT) +#if QT_CONFIG(opengl) void enableOpenGL(bool use_opengl); bool usesOpenGL() { return m_use_opengl; } #endif @@ -129,8 +99,10 @@ protected: void paintEvent(QPaintEvent *) override; void resizeEvent(QResizeEvent *) override; -#if defined(QT_OPENGL_SUPPORT) - GLWidget *glw; +#if QT_CONFIG(opengl) + virtual void createGlWindow(); + QOpenGLWindow *m_glWindow; + QWidget *m_glWidget; bool m_use_opengl; #endif QPixmap m_tile; diff --git a/examples/widgets/painting/shared/fbopaintdevice.cpp b/examples/widgets/painting/shared/fbopaintdevice.cpp new file mode 100644 index 0000000000..8207090cc8 --- /dev/null +++ b/examples/widgets/painting/shared/fbopaintdevice.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "fbopaintdevice.h" + +#include +#include + +QFboPaintDevice::QFboPaintDevice(const QSize& size, bool flipped, bool clearOnInit, + QOpenGLFramebufferObject::Attachment attachment) + : QOpenGLPaintDevice(size) +{ + QOpenGLFramebufferObjectFormat format; + format.setAttachment(attachment); + format.setSamples(4); + m_framebufferObject = new QOpenGLFramebufferObject(size, format); + QOffscreenSurface *surface = new QOffscreenSurface(); + surface->create(); + m_surface = surface; + setPaintFlipped(flipped); + if (clearOnInit) { + m_framebufferObject->bind(); + + context()->functions()->glClearColor(0, 0, 0, 0); + context()->functions()->glClear(GL_COLOR_BUFFER_BIT); + } +} + +QFboPaintDevice::~QFboPaintDevice() +{ + delete m_framebufferObject; + delete m_surface; +} + +void QFboPaintDevice::ensureActiveTarget() +{ + if (QOpenGLContext::currentContext() != context()) + context()->makeCurrent(m_surface); + + m_framebufferObject->bind(); +} + +GLuint QFboPaintDevice::takeTexture() +{ + // We have multisamples so we can't just forward takeTexture(). + QOpenGLFramebufferObject resolvedFbo(m_framebufferObject->size(), m_framebufferObject->attachment()); + QOpenGLFramebufferObject::blitFramebuffer(&resolvedFbo, m_framebufferObject); + return resolvedFbo.takeTexture(); +} + +QImage QFboPaintDevice::toImage() const +{ + QOpenGLContext* currentContext = QOpenGLContext::currentContext(); + QSurface* currentSurface = currentContext ? currentContext->surface() : 0; + + context()->makeCurrent(m_surface); + + QImage image = m_framebufferObject->toImage(!paintFlipped()); + + if (currentContext) + currentContext->makeCurrent(currentSurface); + else + context()->doneCurrent(); + + return image; +} diff --git a/examples/widgets/painting/shared/fbopaintdevice.h b/examples/widgets/painting/shared/fbopaintdevice.h new file mode 100644 index 0000000000..78451af895 --- /dev/null +++ b/examples/widgets/painting/shared/fbopaintdevice.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFBOPAINTDEVICE_H +#define QFBOPAINTDEVICE_H + +#ifndef QT_NO_OPENGL + +#include +#include +#include +#include + +class QFboPaintDevice : public QOpenGLPaintDevice { +public: + QFboPaintDevice(const QSize&, bool flipped = false, bool clearOnInit = true, + QOpenGLFramebufferObject::Attachment = QOpenGLFramebufferObject::CombinedDepthStencil); + ~QFboPaintDevice(); + + // QOpenGLPaintDevice: + void ensureActiveTarget() override; + + bool isValid() const { return m_framebufferObject->isValid(); } + GLuint handle() const { return m_framebufferObject->handle(); } + GLuint takeTexture(); + QImage toImage() const; + + bool bind() { return m_framebufferObject->bind(); } + bool release() { return m_framebufferObject->release(); } + QSize size() const { return m_framebufferObject->size(); } + + QOpenGLFramebufferObject* framebufferObject() { return m_framebufferObject; } + const QOpenGLFramebufferObject* framebufferObject() const { return m_framebufferObject; } + + static bool isSupported() { return QOpenGLFramebufferObject::hasOpenGLFramebufferObjects(); } + +private: + QOpenGLFramebufferObject *m_framebufferObject; + QSurface* m_surface; +}; + +#endif // QT_NO_OPENGL + +#endif // QFBOPAINTDEVICE_H diff --git a/examples/widgets/painting/shared/hoverpoints.cpp b/examples/widgets/painting/shared/hoverpoints.cpp index c735c83f6a..7cd8cc0b29 100644 --- a/examples/widgets/painting/shared/hoverpoints.cpp +++ b/examples/widgets/painting/shared/hoverpoints.cpp @@ -48,10 +48,6 @@ ** ****************************************************************************/ -#ifdef QT_OPENGL_SUPPORT -#include -#endif - #include "arthurwidgets.h" #include "hoverpoints.h" @@ -269,11 +265,6 @@ bool HoverPoints::eventFilter(QObject *object, QEvent *event) QApplication::sendEvent(object, event); m_widget = that_widget; paintPoints(); -#ifdef QT_OPENGL_SUPPORT - ArthurFrame *af = qobject_cast(that_widget); - if (af && af->usesOpenGL()) - af->glWidget()->swapBuffers(); -#endif return true; } default: @@ -288,12 +279,14 @@ bool HoverPoints::eventFilter(QObject *object, QEvent *event) void HoverPoints::paintPoints() { QPainter p; -#ifdef QT_OPENGL_SUPPORT +#if QT_CONFIG(opengl) ArthurFrame *af = qobject_cast(m_widget); - if (af && af->usesOpenGL()) - p.begin(af->glWidget()); - else + if (af && af->usesOpenGL() && af->glWindow()->isValid()) { + af->glWindow()->makeCurrent(); + p.begin(af->glWindow()); + } else { p.begin(m_widget); + } #else p.begin(m_widget); #endif diff --git a/examples/widgets/painting/shared/shared.pri b/examples/widgets/painting/shared/shared.pri index 362cc6819c..cb08b00348 100644 --- a/examples/widgets/painting/shared/shared.pri +++ b/examples/widgets/painting/shared/shared.pri @@ -1,8 +1,8 @@ INCLUDEPATH += $$PWD -qtHaveModule(opengl)|qtConfig(opengles2) { - DEFINES += QT_OPENGL_SUPPORT - QT += opengl widgets +qtConfig(opengl) { + SOURCES += $$PWD/fbopaintdevice.cpp + HEADERS += $$PWD/fbopaintdevice.h } SOURCES += \ -- cgit v1.2.3 From 7aad54262927da7f0223ed9ba970e8bba9f4900d Mon Sep 17 00:00:00 2001 From: Alexander Volkov Date: Wed, 31 Oct 2018 19:50:29 +0300 Subject: Notepad example: Get rid of auto-connection slots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Their correctness is not checked at compile time and even object renames can break code. Change-Id: I99273a28743a79a76c00e6db0ed4cd6d7eba8bf2 Reviewed-by: Topi Reiniö --- examples/widgets/tutorials/gettingstartedqt.qdoc | 14 +++--- examples/widgets/tutorials/notepad/notepad.cpp | 57 +++++++++++++++--------- examples/widgets/tutorials/notepad/notepad.h | 32 ++++++------- 3 files changed, 60 insertions(+), 43 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/tutorials/gettingstartedqt.qdoc b/examples/widgets/tutorials/gettingstartedqt.qdoc index bbe1dd1a8d..32e8845c05 100644 --- a/examples/widgets/tutorials/gettingstartedqt.qdoc +++ b/examples/widgets/tutorials/gettingstartedqt.qdoc @@ -390,10 +390,10 @@ action concerned. When the QAction has been dragged to the toolbar, clicking the icon will launch the associated slot. - Complete the method \c on_actionNew_triggered(): + Complete the method \c newDocument(): \quotefromfile tutorials/notepad/notepad.cpp - \skipto on_actionNew_triggered() + \skipto newDocument() \printuntil } \c current_file is a global variable containing the file presently @@ -411,10 +411,10 @@ In \c notepad.ui, right click on \c actionOpen and select \c {Go to slot} - Complete method \c on_actionOpen_triggered(). + Complete method \c open(). \quotefromfile tutorials/notepad/notepad.cpp - \skipto on_actionOpen_triggered() + \skipto open() \printuntil file.close \printuntil } @@ -436,7 +436,7 @@ \l {Opening a file}, by right clicking on \c actionSave, and selecting \c {Go to Slot}. - \skipto Notepad::on_actionSave_triggered + \skipto Notepad::save \printuntil file.close \printuntil } @@ -449,7 +449,7 @@ \section2 Saving a file with \c {Save as} - \skipto Notepad::on_actionSave_as_triggered + \skipto Notepad::saveAs \printuntil file.close \printuntil } @@ -475,7 +475,7 @@ \section2 Select a Font - \skipto Notepad::on_actionFont_triggered + \skipto Notepad::selectFont \printuntil ui->textEdit->setFont \printline } diff --git a/examples/widgets/tutorials/notepad/notepad.cpp b/examples/widgets/tutorials/notepad/notepad.cpp index d0e600e852..2ccd6501a1 100644 --- a/examples/widgets/tutorials/notepad/notepad.cpp +++ b/examples/widgets/tutorials/notepad/notepad.cpp @@ -74,6 +74,23 @@ Notepad::Notepad(QWidget *parent) : ui->setupUi(this); this->setCentralWidget(ui->textEdit); + connect(ui->actionNew, &QAction::triggered, this, &Notepad::newDocument); + connect(ui->actionOpen, &QAction::triggered, this, &Notepad::open); + connect(ui->actionSave, &QAction::triggered, this, &Notepad::save); + connect(ui->actionSave_as, &QAction::triggered, this, &Notepad::saveAs); + connect(ui->actionPrint, &QAction::triggered, this, &Notepad::print); + connect(ui->actionExit, &QAction::triggered, this, &Notepad::exit); + connect(ui->actionCopy, &QAction::triggered, this, &Notepad::copy); + connect(ui->actionCut, &QAction::triggered, this, &Notepad::cut); + connect(ui->actionPaste, &QAction::triggered, this, &Notepad::paste); + connect(ui->actionUndo, &QAction::triggered, this, &Notepad::undo); + connect(ui->actionRedo, &QAction::triggered, this, &Notepad::redo); + connect(ui->actionFont, &QAction::triggered, this, &Notepad::selectFont); + connect(ui->actionBold, &QAction::triggered, this, &Notepad::setFontBold); + connect(ui->actionUnderline, &QAction::triggered, this, &Notepad::setFontUnderline); + connect(ui->actionItalic, &QAction::triggered, this, &Notepad::setFontItalic); + connect(ui->actionAbout, &QAction::triggered, this, &Notepad::about); + // Disable menu actions for unavailable features #if !QT_CONFIG(printer) ui->actionPrint->setEnabled(false); @@ -91,13 +108,13 @@ Notepad::~Notepad() delete ui; } -void Notepad::on_actionNew_triggered() +void Notepad::newDocument() { currentFile.clear(); ui->textEdit->setText(QString()); } -void Notepad::on_actionOpen_triggered() +void Notepad::open() { QString fileName = QFileDialog::getOpenFileName(this, "Open the file"); QFile file(fileName); @@ -113,7 +130,7 @@ void Notepad::on_actionOpen_triggered() file.close(); } -void Notepad::on_actionSave_triggered() +void Notepad::save() { QString fileName; // If we don't have a filename from before, get one. @@ -135,7 +152,7 @@ void Notepad::on_actionSave_triggered() file.close(); } -void Notepad::on_actionSave_as_triggered() +void Notepad::saveAs() { QString fileName = QFileDialog::getSaveFileName(this, "Save as"); QFile file(fileName); @@ -152,7 +169,7 @@ void Notepad::on_actionSave_as_triggered() file.close(); } -void Notepad::on_actionPrint_triggered() +void Notepad::print() { #if QT_CONFIG(printer) QPrinter printDev; @@ -165,43 +182,43 @@ void Notepad::on_actionPrint_triggered() #endif // QT_CONFIG(printer) } -void Notepad::on_actionExit_triggered() +void Notepad::exit() { QCoreApplication::quit(); } -void Notepad::on_actionCopy_triggered() +void Notepad::copy() { #if QT_CONFIG(clipboard) ui->textEdit->copy(); #endif } -void Notepad::on_actionCut_triggered() +void Notepad::cut() { #if QT_CONFIG(clipboard) ui->textEdit->cut(); #endif } -void Notepad::on_actionPaste_triggered() +void Notepad::paste() { #if QT_CONFIG(clipboard) ui->textEdit->paste(); #endif } -void Notepad::on_actionUndo_triggered() +void Notepad::undo() { ui->textEdit->undo(); } -void Notepad::on_actionRedo_triggered() +void Notepad::redo() { ui->textEdit->redo(); } -void Notepad::on_actionFont_triggered() +void Notepad::selectFont() { bool fontSelected; QFont font = QFontDialog::getFont(&fontSelected, this); @@ -209,23 +226,23 @@ void Notepad::on_actionFont_triggered() ui->textEdit->setFont(font); } -void Notepad::on_actionUnderline_triggered() +void Notepad::setFontUnderline(bool underline) { - ui->textEdit->setFontUnderline(ui->actionUnderline->isChecked()); + ui->textEdit->setFontUnderline(underline); } -void Notepad::on_actionItalic_triggered() +void Notepad::setFontItalic(bool italic) { - ui->textEdit->setFontItalic(ui->actionItalic->isChecked()); + ui->textEdit->setFontItalic(italic); } -void Notepad::on_actionBold_triggered() +void Notepad::setFontBold(bool bold) { - ui->actionBold->isChecked() ? ui->textEdit->setFontWeight(QFont::Bold) : - ui->textEdit->setFontWeight(QFont::Normal); + bold ? ui->textEdit->setFontWeight(QFont::Bold) : + ui->textEdit->setFontWeight(QFont::Normal); } -void Notepad::on_actionAbout_triggered() +void Notepad::about() { QMessageBox::about(this, tr("About MDI"), tr("The Notepad example demonstrates how to code a basic " diff --git a/examples/widgets/tutorials/notepad/notepad.h b/examples/widgets/tutorials/notepad/notepad.h index 288ab4e373..9580ab8071 100644 --- a/examples/widgets/tutorials/notepad/notepad.h +++ b/examples/widgets/tutorials/notepad/notepad.h @@ -79,37 +79,37 @@ public: //! [5] private slots: - void on_actionNew_triggered(); + void newDocument(); - void on_actionOpen_triggered(); + void open(); - void on_actionSave_triggered(); + void save(); - void on_actionSave_as_triggered(); + void saveAs(); - void on_actionPrint_triggered(); + void print(); - void on_actionExit_triggered(); + void exit(); - void on_actionCopy_triggered(); + void copy(); - void on_actionCut_triggered(); + void cut(); - void on_actionPaste_triggered(); + void paste(); - void on_actionUndo_triggered(); + void undo(); - void on_actionRedo_triggered(); + void redo(); - void on_actionFont_triggered(); + void selectFont(); - void on_actionBold_triggered(); + void setFontBold(bool bold); - void on_actionUnderline_triggered(); + void setFontUnderline(bool underline); - void on_actionItalic_triggered(); + void setFontItalic(bool italic); - void on_actionAbout_triggered(); + void about(); //! [6] private: -- cgit v1.2.3 From ae0843eca0e7102390ceec43236cfe8c5724d278 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Thu, 25 Oct 2018 13:48:34 +0200 Subject: Tablet example: Fix warning about switch/fallthrough Add Q_FALLTHROUGH(), fixing: tabletcanvas.cpp:222:55: warning: this statement may fall through [-Wimplicit-fallthrough=] Change-Id: I573f4add56774218e28a7c5f1dac09c5402333c0 Reviewed-by: Shawn Rutledge --- examples/widgets/widgets/tablet/tabletcanvas.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/tablet/tabletcanvas.cpp b/examples/widgets/widgets/tablet/tabletcanvas.cpp index bfcc84e182..dc56702142 100644 --- a/examples/widgets/widgets/tablet/tabletcanvas.cpp +++ b/examples/widgets/widgets/tablet/tabletcanvas.cpp @@ -224,7 +224,7 @@ void TabletCanvas::paintPixmap(QPainter &painter, QTabletEvent *event) qWarning() << error; #endif } - // FALL-THROUGH + Q_FALLTHROUGH(); case QTabletEvent::Stylus: painter.setPen(m_pen); painter.drawLine(lastPoint.pos, event->posF()); -- cgit v1.2.3 From f06e0f62fafcb0eeb725122b2a5321363d417663 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Wed, 31 Oct 2018 21:00:46 +0100 Subject: Fix usage of QGuiApplication::set/resetOverrideCursor Replace all occurrences of QApplication::set/resetOverrideCursor with the QGuiApplication::set/resetOverrideCursor since it's a static function of QGuiApplication. Change-Id: Ic898ab50a7ad4ed2bc9c6acb26cf4a979c2f82af Reviewed-by: Shawn Rutledge --- examples/widgets/mainwindows/application/mainwindow.cpp | 8 ++++---- examples/widgets/mainwindows/dockwidgets/mainwindow.cpp | 4 ++-- examples/widgets/mainwindows/mdi/mdichild.cpp | 8 ++++---- examples/widgets/mainwindows/sdi/mainwindow.cpp | 8 ++++---- examples/widgets/tools/completer/mainwindow.cpp | 4 ++-- examples/widgets/tools/customcompleter/mainwindow.cpp | 4 ++-- examples/widgets/tools/treemodelcompleter/mainwindow.cpp | 4 ++-- 7 files changed, 20 insertions(+), 20 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/mainwindows/application/mainwindow.cpp b/examples/widgets/mainwindows/application/mainwindow.cpp index dc93fe4eb2..4b639ead18 100644 --- a/examples/widgets/mainwindows/application/mainwindow.cpp +++ b/examples/widgets/mainwindows/application/mainwindow.cpp @@ -337,11 +337,11 @@ void MainWindow::loadFile(const QString &fileName) QTextStream in(&file); #ifndef QT_NO_CURSOR - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); #endif textEdit->setPlainText(in.readAll()); #ifndef QT_NO_CURSOR - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); #endif setCurrentFile(fileName); @@ -364,11 +364,11 @@ bool MainWindow::saveFile(const QString &fileName) QTextStream out(&file); #ifndef QT_NO_CURSOR - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); #endif out << textEdit->toPlainText(); #ifndef QT_NO_CURSOR - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); #endif setCurrentFile(fileName); diff --git a/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp b/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp index 47a6e78265..a62765cdab 100644 --- a/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp +++ b/examples/widgets/mainwindows/dockwidgets/mainwindow.cpp @@ -161,9 +161,9 @@ void MainWindow::save() } QTextStream out(&file); - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); out << textEdit->toHtml(); - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); statusBar()->showMessage(tr("Saved '%1'").arg(fileName), 2000); } diff --git a/examples/widgets/mainwindows/mdi/mdichild.cpp b/examples/widgets/mainwindows/mdi/mdichild.cpp index 006c84574a..16f2040de0 100644 --- a/examples/widgets/mainwindows/mdi/mdichild.cpp +++ b/examples/widgets/mainwindows/mdi/mdichild.cpp @@ -82,9 +82,9 @@ bool MdiChild::loadFile(const QString &fileName) } QTextStream in(&file); - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); setPlainText(in.readAll()); - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); setCurrentFile(fileName); @@ -124,9 +124,9 @@ bool MdiChild::saveFile(const QString &fileName) } QTextStream out(&file); - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); out << toPlainText(); - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); setCurrentFile(fileName); return true; diff --git a/examples/widgets/mainwindows/sdi/mainwindow.cpp b/examples/widgets/mainwindows/sdi/mainwindow.cpp index 301c85c144..d44f7c918d 100644 --- a/examples/widgets/mainwindows/sdi/mainwindow.cpp +++ b/examples/widgets/mainwindows/sdi/mainwindow.cpp @@ -338,9 +338,9 @@ void MainWindow::loadFile(const QString &fileName) } QTextStream in(&file); - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); textEdit->setPlainText(in.readAll()); - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); setCurrentFile(fileName); statusBar()->showMessage(tr("File loaded"), 2000); @@ -434,9 +434,9 @@ bool MainWindow::saveFile(const QString &fileName) } QTextStream out(&file); - QApplication::setOverrideCursor(Qt::WaitCursor); + QGuiApplication::setOverrideCursor(Qt::WaitCursor); out << textEdit->toPlainText(); - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); setCurrentFile(fileName); statusBar()->showMessage(tr("File saved"), 2000); diff --git a/examples/widgets/tools/completer/mainwindow.cpp b/examples/widgets/tools/completer/mainwindow.cpp index d63d523548..8eb2e60030 100644 --- a/examples/widgets/tools/completer/mainwindow.cpp +++ b/examples/widgets/tools/completer/mainwindow.cpp @@ -159,7 +159,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) //! [6] #ifndef QT_NO_CURSOR - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #endif QStringList words; @@ -170,7 +170,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) } #ifndef QT_NO_CURSOR - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); #endif //! [6] diff --git a/examples/widgets/tools/customcompleter/mainwindow.cpp b/examples/widgets/tools/customcompleter/mainwindow.cpp index 26948d0c8e..7b9db708b9 100644 --- a/examples/widgets/tools/customcompleter/mainwindow.cpp +++ b/examples/widgets/tools/customcompleter/mainwindow.cpp @@ -100,7 +100,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) return new QStringListModel(completer); #ifndef QT_NO_CURSOR - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #endif QStringList words; @@ -111,7 +111,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) } #ifndef QT_NO_CURSOR - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); #endif return new QStringListModel(words, completer); } diff --git a/examples/widgets/tools/treemodelcompleter/mainwindow.cpp b/examples/widgets/tools/treemodelcompleter/mainwindow.cpp index a8b51c7aa0..72b2fad833 100644 --- a/examples/widgets/tools/treemodelcompleter/mainwindow.cpp +++ b/examples/widgets/tools/treemodelcompleter/mainwindow.cpp @@ -180,7 +180,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) return new QStringListModel(completer); #ifndef QT_NO_CURSOR - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #endif QStringList words; @@ -218,7 +218,7 @@ QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) } #ifndef QT_NO_CURSOR - QApplication::restoreOverrideCursor(); + QGuiApplication::restoreOverrideCursor(); #endif return model; -- cgit v1.2.3 From e9bebc12812b5c50346952cd9128bdd08ddd0b9d Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Thu, 18 Oct 2018 22:45:09 +0200 Subject: Fix use of deprecated ItemDataRoles Background/TextColorRole Replace BackgroundColorRole/TextColorRole with BackgroundRole/ForegroundRole and explicit deprecate them for 5.13 Change-Id: I6b0d99844a32d2f5fdfd1878317a7b7422b800d3 Reviewed-by: Samuel Gaist Reviewed-by: Luca Beldi Reviewed-by: Richard Moe Gustavsen --- examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples/widgets') diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp index 4c18fa8251..92cbaff031 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp @@ -79,7 +79,7 @@ QVariant SpreadSheetItem::data(int role) const bool isNumber = false; int number = t.toInt(&isNumber); - if (role == Qt::TextColorRole) { + if (role == Qt::ForegroundRole) { if (!isNumber) return QVariant::fromValue(QColor(Qt::black)); else if (number < 0) -- cgit v1.2.3 From b5d249f9538bf3dc44f11879c2244deb5a37bf97 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 8 Oct 2018 12:19:01 -0700 Subject: Update the floppy disk icon (save) to be physically correct [ChangeLog][Documentation] Fixed the icons for the "file save" action that were inaccurate representations of a 3.5-inch floppy disk (the cut edge was on the wrong side). Now all floppy representations are physically accurate. Change-Id: Ia3b27ae12a1a4fefa3b7fffd155bb86fee5271c3 Fixes: QTBUG-71012 Reviewed-by: Lars Knoll Reviewed-by: Thiago Macieira --- .../widgets/mainwindows/application/images/save.png | Bin 1187 -> 2699 bytes examples/widgets/mainwindows/mdi/images/save.png | Bin 1187 -> 2699 bytes examples/widgets/mainwindows/sdi/images/save.png | Bin 1187 -> 2699 bytes .../richtext/textedit/images/mac/exportpdf.png | Bin 1215 -> 12637 bytes .../richtext/textedit/images/mac/filesave.png | Bin 1206 -> 2699 bytes .../richtext/textedit/images/win/exportpdf.png | Bin 1059 -> 1215 bytes 6 files changed, 0 insertions(+), 0 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/mainwindows/application/images/save.png b/examples/widgets/mainwindows/application/images/save.png index daba865faf..e65a29d5f1 100644 Binary files a/examples/widgets/mainwindows/application/images/save.png and b/examples/widgets/mainwindows/application/images/save.png differ diff --git a/examples/widgets/mainwindows/mdi/images/save.png b/examples/widgets/mainwindows/mdi/images/save.png index daba865faf..e65a29d5f1 100644 Binary files a/examples/widgets/mainwindows/mdi/images/save.png and b/examples/widgets/mainwindows/mdi/images/save.png differ diff --git a/examples/widgets/mainwindows/sdi/images/save.png b/examples/widgets/mainwindows/sdi/images/save.png index daba865faf..e65a29d5f1 100644 Binary files a/examples/widgets/mainwindows/sdi/images/save.png and b/examples/widgets/mainwindows/sdi/images/save.png differ diff --git a/examples/widgets/richtext/textedit/images/mac/exportpdf.png b/examples/widgets/richtext/textedit/images/mac/exportpdf.png index ebb44e6b88..9e199407af 100644 Binary files a/examples/widgets/richtext/textedit/images/mac/exportpdf.png and b/examples/widgets/richtext/textedit/images/mac/exportpdf.png differ diff --git a/examples/widgets/richtext/textedit/images/mac/filesave.png b/examples/widgets/richtext/textedit/images/mac/filesave.png index b41ecf5319..e65a29d5f1 100644 Binary files a/examples/widgets/richtext/textedit/images/mac/filesave.png and b/examples/widgets/richtext/textedit/images/mac/filesave.png differ diff --git a/examples/widgets/richtext/textedit/images/win/exportpdf.png b/examples/widgets/richtext/textedit/images/win/exportpdf.png index eef5132928..ebb44e6b88 100644 Binary files a/examples/widgets/richtext/textedit/images/win/exportpdf.png and b/examples/widgets/richtext/textedit/images/win/exportpdf.png differ -- cgit v1.2.3 From 6d255b467becad5b5ffebbfa1d13e16b2dd20a64 Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Thu, 1 Nov 2018 15:05:29 +0100 Subject: Fix composition example during OpenGL resizes Previous images were sometimes not cleared correctly. Change-Id: I62949b756bf797aa79c5160774f2f258e5c353dd Reviewed-by: Friedemann Kleint Reviewed-by: Laszlo Agocs --- examples/widgets/painting/composition/composition.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/painting/composition/composition.cpp b/examples/widgets/painting/composition/composition.cpp index 3bc31b1fce..e0abc5875c 100644 --- a/examples/widgets/painting/composition/composition.cpp +++ b/examples/widgets/painting/composition/composition.cpp @@ -358,10 +358,10 @@ void CompositionRenderer::paint(QPainter *painter) m_blitter.create(); int new_pbuf_size = m_pbuffer_size; - if (size().width() > m_pbuffer_size || size().height() > m_pbuffer_size) + while (size().width() > new_pbuf_size || size().height() > new_pbuf_size) new_pbuf_size *= 2; - if (size().width() < m_pbuffer_size/2 && size().height() < m_pbuffer_size/2) + while (size().width() < new_pbuf_size/2 && size().height() < new_pbuf_size/2) new_pbuf_size /= 2; if (!m_fbo || new_pbuf_size != m_pbuffer_size) { @@ -372,6 +372,9 @@ void CompositionRenderer::paint(QPainter *painter) if (size() != m_previous_size) { m_previous_size = size(); QPainter p(m_fbo.data()); + p.setCompositionMode(QPainter::CompositionMode_Source); + p.fillRect(QRect(QPoint(0, 0), size()), Qt::transparent); + p.setCompositionMode(QPainter::CompositionMode_SourceOver); drawBase(p); p.end(); m_base_tex = m_fbo->takeTexture(); -- cgit v1.2.3 From 8c685b765bf4ceba3c4cf8fdd9c9d680f338b7a9 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sat, 20 Oct 2018 21:48:28 +0200 Subject: Itemviews: Cleanup examples MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cleanup some minor issues in the chart example: - remove unused members - use initializer list for members - pass a proper role to dataChanged() - honor roles parameter in PieView::dataChanged() - use nullptr instead 0 - use new-style connect - fix indentation and other whitespaces Change-Id: Idb212b07c006fe3ae31bee9cd9b1ba4d03043b5e Reviewed-by: André Hartmann Reviewed-by: Paul Wicking --- .../widgets/itemviews/addressbook/tablemodel.cpp | 2 +- examples/widgets/itemviews/chart/mainwindow.cpp | 18 +++---- examples/widgets/itemviews/chart/mainwindow.h | 8 ++-- examples/widgets/itemviews/chart/pieview.cpp | 56 ++++++++++------------ examples/widgets/itemviews/chart/pieview.h | 14 +++--- .../itemviews/editabletreemodel/treemodel.cpp | 2 +- .../tutorials/modelview/1_readonly/main.cpp | 8 ++-- .../tutorials/modelview/1_readonly/mymodel.cpp | 5 +- .../tutorials/modelview/1_readonly/mymodel.h | 4 +- .../tutorials/modelview/2_formatting/main.cpp | 8 ++-- .../tutorials/modelview/2_formatting/mymodel.cpp | 24 +++------- .../tutorials/modelview/2_formatting/mymodel.h | 4 +- .../tutorials/modelview/3_changingmodel/main.cpp | 6 +-- .../modelview/3_changingmodel/mymodel.cpp | 23 ++++----- .../tutorials/modelview/3_changingmodel/mymodel.h | 7 ++- .../widgets/tutorials/modelview/4_headers/main.cpp | 10 ++-- .../tutorials/modelview/4_headers/mymodel.cpp | 25 ++++------ .../tutorials/modelview/4_headers/mymodel.h | 4 +- .../widgets/tutorials/modelview/5_edit/main.cpp | 2 +- .../tutorials/modelview/5_edit/mainwindow.cpp | 14 +++--- .../tutorials/modelview/5_edit/mainwindow.h | 8 ++-- .../widgets/tutorials/modelview/5_edit/mymodel.cpp | 30 +++++------- .../widgets/tutorials/modelview/5_edit/mymodel.h | 8 ++-- .../tutorials/modelview/6_treeview/main.cpp | 2 +- .../tutorials/modelview/6_treeview/mainwindow.cpp | 23 +++++---- .../tutorials/modelview/6_treeview/mainwindow.h | 12 ++--- .../tutorials/modelview/7_selections/main.cpp | 2 +- .../modelview/7_selections/mainwindow.cpp | 18 +++---- .../tutorials/modelview/7_selections/mainwindow.h | 6 +-- 29 files changed, 161 insertions(+), 192 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/itemviews/addressbook/tablemodel.cpp b/examples/widgets/itemviews/addressbook/tablemodel.cpp index 674e312753..b3704f857e 100644 --- a/examples/widgets/itemviews/addressbook/tablemodel.cpp +++ b/examples/widgets/itemviews/addressbook/tablemodel.cpp @@ -164,7 +164,7 @@ bool TableModel::setData(const QModelIndex &index, const QVariant &value, int ro return false; contacts.replace(row, contact); - emit(dataChanged(index, index)); + emit dataChanged(index, index, {role}); return true; } diff --git a/examples/widgets/itemviews/chart/mainwindow.cpp b/examples/widgets/itemviews/chart/mainwindow.cpp index 91e535a006..53f57fbb49 100644 --- a/examples/widgets/itemviews/chart/mainwindow.cpp +++ b/examples/widgets/itemviews/chart/mainwindow.cpp @@ -48,12 +48,13 @@ ** ****************************************************************************/ -#include - #include "pieview.h" #include "mainwindow.h" -MainWindow::MainWindow() +#include + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) { QMenu *fileMenu = new QMenu(tr("&File"), this); QAction *openAction = fileMenu->addAction(tr("&Open...")); @@ -124,17 +125,18 @@ void MainWindow::loadFile(const QString &fileName) return; QTextStream stream(&file); - QString line; model->removeRows(0, model->rowCount(QModelIndex()), QModelIndex()); int row = 0; - do { - line = stream.readLine(); + while (!stream.atEnd()) { + const QString line = stream.readLine(); if (!line.isEmpty()) { model->insertRows(row, 1, QModelIndex()); - QStringList pieces = line.split(',', QString::SkipEmptyParts); + const QStringList pieces = line.split(',', QString::SkipEmptyParts); + if (pieces.size() < 3) + continue; model->setData(model->index(row, 0, QModelIndex()), pieces.value(0)); model->setData(model->index(row, 1, QModelIndex()), @@ -143,7 +145,7 @@ void MainWindow::loadFile(const QString &fileName) QColor(pieces.value(2)), Qt::DecorationRole); row++; } - } while (!line.isEmpty()); + }; file.close(); statusBar()->showMessage(tr("Loaded %1").arg(fileName), 2000); diff --git a/examples/widgets/itemviews/chart/mainwindow.h b/examples/widgets/itemviews/chart/mainwindow.h index 058f5c7e90..51176d261b 100644 --- a/examples/widgets/itemviews/chart/mainwindow.h +++ b/examples/widgets/itemviews/chart/mainwindow.h @@ -56,7 +56,6 @@ QT_BEGIN_NAMESPACE class QAbstractItemModel; class QAbstractItemView; -class QItemSelectionModel; QT_END_NAMESPACE class MainWindow : public QMainWindow @@ -64,7 +63,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); private slots: void openFile(); @@ -75,9 +74,8 @@ private: void setupViews(); void loadFile(const QString &path); - QAbstractItemModel *model; - QAbstractItemView *pieChart; - QItemSelectionModel *selectionModel; + QAbstractItemModel *model = nullptr; + QAbstractItemView *pieChart = nullptr; }; #endif // MAINWINDOW_H diff --git a/examples/widgets/itemviews/chart/pieview.cpp b/examples/widgets/itemviews/chart/pieview.cpp index 3f85e397ee..457ed8b4ec 100644 --- a/examples/widgets/itemviews/chart/pieview.cpp +++ b/examples/widgets/itemviews/chart/pieview.cpp @@ -48,30 +48,25 @@ ** ****************************************************************************/ -#include -#include -#include #include "pieview.h" +#include + PieView::PieView(QWidget *parent) : QAbstractItemView(parent) { horizontalScrollBar()->setRange(0, 0); verticalScrollBar()->setRange(0, 0); - - margin = 8; - totalSize = 300; - pieSize = totalSize - 2 * margin; - validItems = 0; - totalValue = 0.0; - rubberBand = 0; } void PieView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, - const QVector &) + const QVector &roles) { - QAbstractItemView::dataChanged(topLeft, bottomRight); + QAbstractItemView::dataChanged(topLeft, bottomRight, roles); + + if (!roles.contains(Qt::DisplayRole)) + return; validItems = 0; totalValue = 0.0; @@ -79,7 +74,7 @@ void PieView::dataChanged(const QModelIndex &topLeft, for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { QModelIndex index = model()->index(row, 1, rootIndex()); - double value = model()->data(index).toDouble(); + double value = model()->data(index, Qt::DisplayRole).toDouble(); if (value > 0.0) { totalValue += value; @@ -197,15 +192,14 @@ QRect PieView::itemRect(const QModelIndex &index) const listItem++; } - double itemHeight; - switch (index.column()) { - case 0: - itemHeight = QFontMetrics(viewOptions().font).height(); + case 0: { + const qreal itemHeight = QFontMetricsF(viewOptions().font).height(); return QRect(totalSize, - int(margin + listItem*itemHeight), - totalSize - margin, int(itemHeight)); + qRound(margin + listItem * itemHeight), + totalSize - margin, qRound(itemHeight)); + } case 1: return viewport()->rect(); } @@ -235,7 +229,7 @@ QRegion PieView::itemRegion(const QModelIndex &index) const if (sliceIndex == index) { QPainterPath slicePath; slicePath.moveTo(totalSize / 2, totalSize / 2); - slicePath.arcTo(margin, margin, margin+pieSize, margin+pieSize, + slicePath.arcTo(margin, margin, margin + pieSize, margin + pieSize, startAngle, angle); slicePath.closeSubpath(); @@ -342,7 +336,7 @@ void PieView::paintEvent(QPaintEvent *event) double value = model()->data(index).toDouble(); if (value > 0.0) { - double angle = 360*value/totalValue; + double angle = 360 * value / totalValue; QModelIndex colorIndex = model()->index(row, 0, rootIndex()); QColor color = QColor(model()->data(colorIndex, Qt::DecorationRole).toString()); @@ -480,16 +474,16 @@ void PieView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlag } if (indexes.size() > 0) { - int firstRow = indexes[0].row(); - int lastRow = indexes[0].row(); - int firstColumn = indexes[0].column(); - int lastColumn = indexes[0].column(); + int firstRow = indexes.at(0).row(); + int lastRow = firstRow; + int firstColumn = indexes.at(0).column(); + int lastColumn = firstColumn; for (int i = 1; i < indexes.size(); ++i) { - firstRow = qMin(firstRow, indexes[i].row()); - lastRow = qMax(lastRow, indexes[i].row()); - firstColumn = qMin(firstColumn, indexes[i].column()); - lastColumn = qMax(lastColumn, indexes[i].column()); + firstRow = qMin(firstRow, indexes.at(i).row()); + lastRow = qMax(lastRow, indexes.at(i).row()); + firstColumn = qMin(firstColumn, indexes.at(i).column()); + lastColumn = qMax(lastColumn, indexes.at(i).column()); } QItemSelection selection( @@ -508,7 +502,7 @@ void PieView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlag void PieView::updateGeometries() { horizontalScrollBar()->setPageStep(viewport()->width()); - horizontalScrollBar()->setRange(0, qMax(0, 2*totalSize - viewport()->width())); + horizontalScrollBar()->setRange(0, qMax(0, 2 * totalSize - viewport()->width())); verticalScrollBar()->setPageStep(viewport()->height()); verticalScrollBar()->setRange(0, qMax(0, totalSize - viewport()->height())); } @@ -546,7 +540,7 @@ QRegion PieView::visualRegionForSelection(const QItemSelection &selection) const QRegion region; for (int i = 0; i < ranges; ++i) { - QItemSelectionRange range = selection.at(i); + const QItemSelectionRange &range = selection.at(i); for (int row = range.top(); row <= range.bottom(); ++row) { for (int col = range.left(); col <= range.right(); ++col) { QModelIndex index = model()->index(row, col, rootIndex()); diff --git a/examples/widgets/itemviews/chart/pieview.h b/examples/widgets/itemviews/chart/pieview.h index aa397e6d55..22c74dde81 100644 --- a/examples/widgets/itemviews/chart/pieview.h +++ b/examples/widgets/itemviews/chart/pieview.h @@ -59,7 +59,7 @@ class PieView : public QAbstractItemView Q_OBJECT public: - PieView(QWidget *parent = 0); + PieView(QWidget *parent = nullptr); QRect visualRect(const QModelIndex &index) const override; void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible) override; @@ -100,13 +100,13 @@ private: int rows(const QModelIndex &index = QModelIndex()) const; void updateGeometries() override; - int margin; - int totalSize; - int pieSize; - int validItems; - double totalValue; + int margin = 0; + int totalSize = 300; + int pieSize = totalSize - 2 * margin; + int validItems = 0; + double totalValue = 0.0; + QRubberBand *rubberBand = nullptr; QPoint origin; - QRubberBand *rubberBand; }; //! [0] diff --git a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp index dbd53df1e6..72818372d7 100644 --- a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp +++ b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp @@ -225,7 +225,7 @@ bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int rol bool result = item->setData(index.column(), value); if (result) - emit dataChanged(index, index); + emit dataChanged(index, index, {role}); return result; } diff --git a/examples/widgets/tutorials/modelview/1_readonly/main.cpp b/examples/widgets/tutorials/modelview/1_readonly/main.cpp index 80383f8c94..ea571d3699 100644 --- a/examples/widgets/tutorials/modelview/1_readonly/main.cpp +++ b/examples/widgets/tutorials/modelview/1_readonly/main.cpp @@ -50,16 +50,16 @@ //! [Quoting ModelView Tutorial] // main.cpp -#include -#include +#include +#include #include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTableView tableView; - MyModel myModel(0); - tableView.setModel( &myModel ); + MyModel myModel; + tableView.setModel(&myModel); tableView.show(); return a.exec(); } diff --git a/examples/widgets/tutorials/modelview/1_readonly/mymodel.cpp b/examples/widgets/tutorials/modelview/1_readonly/mymodel.cpp index 82ec53c665..2b36565bc6 100644 --- a/examples/widgets/tutorials/modelview/1_readonly/mymodel.cpp +++ b/examples/widgets/tutorials/modelview/1_readonly/mymodel.cpp @@ -53,7 +53,7 @@ #include "mymodel.h" MyModel::MyModel(QObject *parent) - :QAbstractTableModel(parent) + : QAbstractTableModel(parent) { } @@ -70,11 +70,10 @@ int MyModel::columnCount(const QModelIndex & /*parent*/) const QVariant MyModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) - { return QString("Row%1, Column%2") .arg(index.row() + 1) .arg(index.column() +1); - } + return QVariant(); } //! [Quoting ModelView Tutorial] diff --git a/examples/widgets/tutorials/modelview/1_readonly/mymodel.h b/examples/widgets/tutorials/modelview/1_readonly/mymodel.h index e675cc6bc2..8761322896 100644 --- a/examples/widgets/tutorials/modelview/1_readonly/mymodel.h +++ b/examples/widgets/tutorials/modelview/1_readonly/mymodel.h @@ -59,8 +59,8 @@ class MyModel : public QAbstractTableModel { Q_OBJECT public: - MyModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const override ; + MyModel(QObject *parent = nullptr); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; }; diff --git a/examples/widgets/tutorials/modelview/2_formatting/main.cpp b/examples/widgets/tutorials/modelview/2_formatting/main.cpp index 80383f8c94..ea571d3699 100644 --- a/examples/widgets/tutorials/modelview/2_formatting/main.cpp +++ b/examples/widgets/tutorials/modelview/2_formatting/main.cpp @@ -50,16 +50,16 @@ //! [Quoting ModelView Tutorial] // main.cpp -#include -#include +#include +#include #include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTableView tableView; - MyModel myModel(0); - tableView.setModel( &myModel ); + MyModel myModel; + tableView.setModel(&myModel); tableView.show(); return a.exec(); } diff --git a/examples/widgets/tutorials/modelview/2_formatting/mymodel.cpp b/examples/widgets/tutorials/modelview/2_formatting/mymodel.cpp index 9511648392..938597a34e 100644 --- a/examples/widgets/tutorials/modelview/2_formatting/mymodel.cpp +++ b/examples/widgets/tutorials/modelview/2_formatting/mymodel.cpp @@ -48,13 +48,14 @@ ** ****************************************************************************/ +#include "mymodel.h" + #include #include -#include "mymodel.h" #include MyModel::MyModel(QObject *parent) - :QAbstractTableModel(parent) + : QAbstractTableModel(parent) { } @@ -78,7 +79,7 @@ QVariant MyModel::data(const QModelIndex &index, int role) const qDebug() << QString("row %1, col%2, role %3") .arg(row).arg(col).arg(role); - switch(role){ + switch (role) { case Qt::DisplayRole: if (row == 0 && col == 1) return QString("<--left"); if (row == 1 && col == 1) return QString("right-->"); @@ -86,36 +87,25 @@ QVariant MyModel::data(const QModelIndex &index, int role) const return QString("Row%1, Column%2") .arg(row + 1) .arg(col +1); - break; case Qt::FontRole: - if (row == 0 && col == 0) //change font only for cell(0,0) - { + if (row == 0 && col == 0) { //change font only for cell(0,0) QFont boldFont; boldFont.setBold(true); return boldFont; } break; case Qt::BackgroundRole: - if (row == 1 && col == 2) //change background only for cell(1,2) - { - QBrush redBackground(Qt::red); - return redBackground; - } + return QBrush(Qt::red); break; case Qt::TextAlignmentRole: - if (row == 1 && col == 1) //change text alignment only for cell(1,1) - { return Qt::AlignRight + Qt::AlignVCenter; - } break; case Qt::CheckStateRole: - if (row == 1 && col == 0) //add a checkbox to cell(1,0) - { return Qt::Checked; - } + break; } return QVariant(); } diff --git a/examples/widgets/tutorials/modelview/2_formatting/mymodel.h b/examples/widgets/tutorials/modelview/2_formatting/mymodel.h index 9c12f98ba9..e8ae673f62 100644 --- a/examples/widgets/tutorials/modelview/2_formatting/mymodel.h +++ b/examples/widgets/tutorials/modelview/2_formatting/mymodel.h @@ -57,8 +57,8 @@ class MyModel : public QAbstractTableModel { Q_OBJECT public: - MyModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const override ; + MyModel(QObject *parent = nullptr); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; }; diff --git a/examples/widgets/tutorials/modelview/3_changingmodel/main.cpp b/examples/widgets/tutorials/modelview/3_changingmodel/main.cpp index c03019a910..2330019f93 100644 --- a/examples/widgets/tutorials/modelview/3_changingmodel/main.cpp +++ b/examples/widgets/tutorials/modelview/3_changingmodel/main.cpp @@ -48,8 +48,8 @@ ** ****************************************************************************/ -#include -#include +#include +#include #include "mymodel.h" int main(int argc, char *argv[]) @@ -57,7 +57,7 @@ int main(int argc, char *argv[]) QApplication a(argc, argv); QTableView tableView; MyModel myModel(0); - tableView.setModel( &myModel ); + tableView.setModel(&myModel); tableView.show(); return a.exec(); } diff --git a/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.cpp b/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.cpp index e4580a0e01..f289d9abda 100644 --- a/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.cpp +++ b/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.cpp @@ -48,18 +48,17 @@ ** ****************************************************************************/ -#include -#include #include "mymodel.h" +#include + //! [quoting mymodel_a] MyModel::MyModel(QObject *parent) - :QAbstractTableModel(parent) + : QAbstractTableModel(parent) + , timer(new QTimer(this)) { -// selectedCell = 0; - timer = new QTimer(this); timer->setInterval(1000); - connect(timer, SIGNAL(timeout()) , this, SLOT(timerHit())); + connect(timer, &QTimer::timeout , this, &MyModel::timerHit); timer->start(); } //! [quoting mymodel_a] @@ -82,13 +81,9 @@ QVariant MyModel::data(const QModelIndex &index, int role) const int row = index.row(); int col = index.column(); - if (role == Qt::DisplayRole) - { - if (row == 0 && col == 0) - { - return QTime::currentTime().toString(); - } - } + if (role == Qt::DisplayRole && row == 0 && col == 0) + return QTime::currentTime().toString(); + return QVariant(); } //! [quoting mymodel_QVariant ] @@ -99,6 +94,6 @@ void MyModel::timerHit() //we identify the top left cell QModelIndex topLeft = createIndex(0,0); //emit a signal to make the view reread identified data - emit dataChanged(topLeft, topLeft); + emit dataChanged(topLeft, topLeft, {Qt::DisplayRole}); } //! [quoting mymodel_b ] diff --git a/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.h b/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.h index dfcf0f6239..2ef0e480c2 100644 --- a/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.h +++ b/examples/widgets/tutorials/modelview/3_changingmodel/mymodel.h @@ -58,13 +58,12 @@ class MyModel : public QAbstractTableModel { Q_OBJECT public: - MyModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const override ; + MyModel(QObject *parent = nullptr); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QTimer *timer; private: - int selectedCell; + QTimer *timer; private slots: void timerHit(); }; diff --git a/examples/widgets/tutorials/modelview/4_headers/main.cpp b/examples/widgets/tutorials/modelview/4_headers/main.cpp index 82d493345d..90a8c6e894 100644 --- a/examples/widgets/tutorials/modelview/4_headers/main.cpp +++ b/examples/widgets/tutorials/modelview/4_headers/main.cpp @@ -48,16 +48,16 @@ ** ****************************************************************************/ -#include -#include +#include +#include #include "mymodel.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTableView tableView; - MyModel myModel(0); - tableView.setModel( &myModel ); + MyModel myModel; + tableView.setModel(&myModel); tableView.show(); return a.exec(); -} \ No newline at end of file +} diff --git a/examples/widgets/tutorials/modelview/4_headers/mymodel.cpp b/examples/widgets/tutorials/modelview/4_headers/mymodel.cpp index 35e3463b7f..0084475374 100644 --- a/examples/widgets/tutorials/modelview/4_headers/mymodel.cpp +++ b/examples/widgets/tutorials/modelview/4_headers/mymodel.cpp @@ -51,7 +51,7 @@ #include "mymodel.h" MyModel::MyModel(QObject *parent) - :QAbstractTableModel(parent) + : QAbstractTableModel(parent) { } @@ -70,8 +70,7 @@ int MyModel::columnCount(const QModelIndex & /*parent*/) const //------------------------------------------------------- QVariant MyModel::data(const QModelIndex &index, int role) const { - if (role == Qt::DisplayRole) - { + if (role == Qt::DisplayRole) { return QString("Row%1, Column%2") .arg(index.row() + 1) .arg(index.column() +1); @@ -82,18 +81,14 @@ QVariant MyModel::data(const QModelIndex &index, int role) const //! [quoting mymodel_c] QVariant MyModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role == Qt::DisplayRole) - { - if (orientation == Qt::Horizontal) { - switch (section) - { - case 0: - return QString("first"); - case 1: - return QString("second"); - case 2: - return QString("third"); - } + if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { + switch (section) { + case 0: + return QString("first"); + case 1: + return QString("second"); + case 2: + return QString("third"); } } return QVariant(); diff --git a/examples/widgets/tutorials/modelview/4_headers/mymodel.h b/examples/widgets/tutorials/modelview/4_headers/mymodel.h index fb2d7aa940..6d8477dae2 100644 --- a/examples/widgets/tutorials/modelview/4_headers/mymodel.h +++ b/examples/widgets/tutorials/modelview/4_headers/mymodel.h @@ -57,8 +57,8 @@ class MyModel : public QAbstractTableModel { Q_OBJECT public: - MyModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const override ; + MyModel(QObject *parent = nullptr); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; diff --git a/examples/widgets/tutorials/modelview/5_edit/main.cpp b/examples/widgets/tutorials/modelview/5_edit/main.cpp index e1b46339b1..315875a627 100644 --- a/examples/widgets/tutorials/modelview/5_edit/main.cpp +++ b/examples/widgets/tutorials/modelview/5_edit/main.cpp @@ -48,7 +48,7 @@ ** ****************************************************************************/ -#include +#include #include "mainwindow.h" int main(int argc, char *argv[]) diff --git a/examples/widgets/tutorials/modelview/5_edit/mainwindow.cpp b/examples/widgets/tutorials/modelview/5_edit/mainwindow.cpp index e0b6ea7b1f..d8dfc33212 100644 --- a/examples/widgets/tutorials/modelview/5_edit/mainwindow.cpp +++ b/examples/widgets/tutorials/modelview/5_edit/mainwindow.cpp @@ -48,23 +48,25 @@ ** ****************************************************************************/ -#include #include "mainwindow.h" #include "mymodel.h" +#include + MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) + , tableView(new QTableView(this)) { - tableView = new QTableView(this); setCentralWidget(tableView); - QAbstractTableModel *myModel = new MyModel(this); + MyModel *myModel = new MyModel(this); tableView->setModel(myModel); //transfer changes to the model to the window title - connect(myModel, SIGNAL(editCompleted(const QString &)), this, SLOT(setWindowTitle(const QString &))); + connect(myModel, &MyModel::editCompleted, + this, &MainWindow::showWindowTitle); } -void MainWindow::showWindowTitle(const QString & title) +void MainWindow::showWindowTitle(const QString &title) { -setWindowTitle(title); + setWindowTitle(title); } diff --git a/examples/widgets/tutorials/modelview/5_edit/mainwindow.h b/examples/widgets/tutorials/modelview/5_edit/mainwindow.h index 7915b29cdf..104f06f82e 100644 --- a/examples/widgets/tutorials/modelview/5_edit/mainwindow.h +++ b/examples/widgets/tutorials/modelview/5_edit/mainwindow.h @@ -51,9 +51,9 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include +#include -QT_BEGIN_NAMESPACE // QT_BEGIN_NAMESPACE / QT_END_NAMESPACE are not needed in Qt user code +QT_BEGIN_NAMESPACE class QTableView; //forward declaration QT_END_NAMESPACE @@ -64,9 +64,9 @@ class MainWindow : public QMainWindow private: QTableView *tableView; public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); public slots: - void showWindowTitle(const QString & title); + void showWindowTitle(const QString &title); }; #endif // MAINWINDOW_H diff --git a/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp b/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp index fb2954baf2..eeca2ce0a0 100644 --- a/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp +++ b/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp @@ -48,12 +48,10 @@ ** ****************************************************************************/ - #include "mymodel.h" - MyModel::MyModel(QObject *parent) - :QAbstractTableModel(parent) + : QAbstractTableModel(parent) { } @@ -72,33 +70,31 @@ int MyModel::columnCount(const QModelIndex & /*parent*/) const //----------------------------------------------------------------- QVariant MyModel::data(const QModelIndex &index, int role) const { - if (role == Qt::DisplayRole) - { - return m_gridData[index.row()][index.column()]; - } + if (role == Qt::DisplayRole && checkIndex(index)) + return m_gridData[index.row()][index.column()]; + return QVariant(); } //----------------------------------------------------------------- //! [quoting mymodel_e] -bool MyModel::setData(const QModelIndex & index, const QVariant & value, int role) +bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if (role == Qt::EditRole) - { + if (role == Qt::EditRole) { + if (!checkIndex(index)) + return false; //save value from editor to member m_gridData m_gridData[index.row()][index.column()] = value.toString(); //for presentation purposes only: build and emit a joined string QString result; - for (int row= 0; row < ROWS; row++) - { - for(int col= 0; col < COLS; col++) - { + for (int row = 0; row < ROWS; row++) { + for (int col= 0; col < COLS; col++) result += m_gridData[row][col] + ' '; - } } - emit editCompleted( result ); + emit editCompleted(result); + return true; } - return true; + return false; } //! [quoting mymodel_e] diff --git a/examples/widgets/tutorials/modelview/5_edit/mymodel.h b/examples/widgets/tutorials/modelview/5_edit/mymodel.h index dd0d4f5066..ce462351af 100644 --- a/examples/widgets/tutorials/modelview/5_edit/mymodel.h +++ b/examples/widgets/tutorials/modelview/5_edit/mymodel.h @@ -64,12 +64,12 @@ class MyModel : public QAbstractTableModel { Q_OBJECT public: - MyModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const override ; + MyModel(QObject *parent = nullptr); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex & index) const override ; + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &index) const override; private: QString m_gridData[ROWS][COLS]; //holds text entered into QTableView signals: diff --git a/examples/widgets/tutorials/modelview/6_treeview/main.cpp b/examples/widgets/tutorials/modelview/6_treeview/main.cpp index e1b46339b1..315875a627 100644 --- a/examples/widgets/tutorials/modelview/6_treeview/main.cpp +++ b/examples/widgets/tutorials/modelview/6_treeview/main.cpp @@ -48,7 +48,7 @@ ** ****************************************************************************/ -#include +#include #include "mainwindow.h" int main(int argc, char *argv[]) diff --git a/examples/widgets/tutorials/modelview/6_treeview/mainwindow.cpp b/examples/widgets/tutorials/modelview/6_treeview/mainwindow.cpp index 1016afba07..ae4a343680 100644 --- a/examples/widgets/tutorials/modelview/6_treeview/mainwindow.cpp +++ b/examples/widgets/tutorials/modelview/6_treeview/mainwindow.cpp @@ -50,24 +50,25 @@ //! [Quoting ModelView Tutorial] // modelview.cpp +#include "mainwindow.h" + #include #include #include -#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) + , treeView(new QTreeView(this)) + , standardModel(new QStandardItemModel(this)) { - treeView = new QTreeView(this); setCentralWidget(treeView); - standardModel = new QStandardItemModel ; - QList preparedRow =prepareRow("first", "second", "third"); + QList preparedRow = prepareRow("first", "second", "third"); QStandardItem *item = standardModel->invisibleRootItem(); // adding a row to the invisible root item produces a root element item->appendRow(preparedRow); - QList secondRow =prepareRow("111", "222", "333"); + QList secondRow = prepareRow("111", "222", "333"); // adding a row to an item starts a subtree preparedRow.first()->appendRow(secondRow); @@ -76,13 +77,11 @@ MainWindow::MainWindow(QWidget *parent) } QList MainWindow::prepareRow(const QString &first, - const QString &second, - const QString &third) + const QString &second, + const QString &third) const { - QList rowItems; - rowItems << new QStandardItem(first); - rowItems << new QStandardItem(second); - rowItems << new QStandardItem(third); - return rowItems; + return {new QStandardItem(first), + new QStandardItem(second), + new QStandardItem(third)}; } //! [Quoting ModelView Tutorial] diff --git a/examples/widgets/tutorials/modelview/6_treeview/mainwindow.h b/examples/widgets/tutorials/modelview/6_treeview/mainwindow.h index d625d5991d..65d9c18658 100644 --- a/examples/widgets/tutorials/modelview/6_treeview/mainwindow.h +++ b/examples/widgets/tutorials/modelview/6_treeview/mainwindow.h @@ -51,9 +51,9 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include +#include -QT_BEGIN_NAMESPACE // QT_BEGIN_NAMESPACE / QT_END_NAMESPACE are not needed in Qt user code +QT_BEGIN_NAMESPACE class QTreeView; //forward declarations class QStandardItemModel; class QStandardItem; @@ -66,11 +66,11 @@ class MainWindow : public QMainWindow private: QTreeView *treeView; QStandardItemModel *standardModel; - QList prepareRow( const QString &first, - const QString &second, - const QString &third ); + QList prepareRow(const QString &first, + const QString &second, + const QString &third) const; public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); }; #endif // MAINWINDOW_H diff --git a/examples/widgets/tutorials/modelview/7_selections/main.cpp b/examples/widgets/tutorials/modelview/7_selections/main.cpp index e1b46339b1..315875a627 100644 --- a/examples/widgets/tutorials/modelview/7_selections/main.cpp +++ b/examples/widgets/tutorials/modelview/7_selections/main.cpp @@ -48,7 +48,7 @@ ** ****************************************************************************/ -#include +#include #include "mainwindow.h" int main(int argc, char *argv[]) diff --git a/examples/widgets/tutorials/modelview/7_selections/mainwindow.cpp b/examples/widgets/tutorials/modelview/7_selections/mainwindow.cpp index 200751ee6d..2b10071a68 100644 --- a/examples/widgets/tutorials/modelview/7_selections/mainwindow.cpp +++ b/examples/widgets/tutorials/modelview/7_selections/mainwindow.cpp @@ -49,17 +49,18 @@ ****************************************************************************/ //! [quoting modelview_a] +#include "mainwindow.h" + #include #include #include -#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) + , treeView(new QTreeView(this)) + , standardModel(new QStandardItemModel(this)) { - treeView = new QTreeView(this); setCentralWidget(treeView); - standardModel = new QStandardItemModel ; QStandardItem *rootNode = standardModel->invisibleRootItem(); @@ -88,9 +89,9 @@ MainWindow::MainWindow(QWidget *parent) treeView->expandAll(); //selection changes shall trigger a slot - QItemSelectionModel *selectionModel= treeView->selectionModel(); - connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)), - this, SLOT(selectionChangedSlot(const QItemSelection &, const QItemSelection &))); + QItemSelectionModel *selectionModel = treeView->selectionModel(); + connect(selectionModel, &QItemSelectionModel::selectionChanged, + this, &MainWindow::selectionChangedSlot); } //! [quoting modelview_a] @@ -103,10 +104,9 @@ void MainWindow::selectionChangedSlot(const QItemSelection & /*newSelection*/, c const QModelIndex index = treeView->selectionModel()->currentIndex(); QString selectedText = index.data(Qt::DisplayRole).toString(); //find out the hierarchy level of the selected item - int hierarchyLevel=1; + int hierarchyLevel = 1; QModelIndex seekRoot = index; - while(seekRoot.parent() != QModelIndex()) - { + while (seekRoot.parent() != QModelIndex()) { seekRoot = seekRoot.parent(); hierarchyLevel++; } diff --git a/examples/widgets/tutorials/modelview/7_selections/mainwindow.h b/examples/widgets/tutorials/modelview/7_selections/mainwindow.h index 13ca7dbc30..c9761dd3d9 100644 --- a/examples/widgets/tutorials/modelview/7_selections/mainwindow.h +++ b/examples/widgets/tutorials/modelview/7_selections/mainwindow.h @@ -51,9 +51,9 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include +#include -QT_BEGIN_NAMESPACE // QT_BEGIN_NAMESPACE / QT_END_NAMESPACE are not needed in Qt user code +QT_BEGIN_NAMESPACE class QTreeView; //forward declarations class QStandardItemModel; class QItemSelection; @@ -67,7 +67,7 @@ private: QTreeView *treeView; QStandardItemModel *standardModel; private slots: - void selectionChangedSlot(const QItemSelection & newSelection, const QItemSelection & oldSelection); + void selectionChangedSlot(const QItemSelection &newSelection, const QItemSelection &oldSelection); public: MainWindow(QWidget *parent = 0); }; -- cgit v1.2.3 From 8b42614c6cee227200fdf67082d29a0f0b9adf9d Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Tue, 13 Nov 2018 20:43:58 +0100 Subject: Cleanup Spreadsheet example Cleanup the Spreadsheet example: - use nullptr - use for instead foreach Change-Id: I55deed157403a46d98a6d753ef46e4cbe5730b4f Reviewed-by: Luca Beldi Reviewed-by: Paul Wicking Reviewed-by: Sze Howe Koh --- examples/widgets/itemviews/spreadsheet/main.cpp | 3 +- .../widgets/itemviews/spreadsheet/printview.cpp | 5 +- .../widgets/itemviews/spreadsheet/spreadsheet.cpp | 56 ++++++++++------------ .../widgets/itemviews/spreadsheet/spreadsheet.h | 4 +- .../itemviews/spreadsheet/spreadsheetdelegate.cpp | 12 +++-- .../itemviews/spreadsheet/spreadsheetdelegate.h | 4 +- .../itemviews/spreadsheet/spreadsheetitem.cpp | 33 +++++-------- .../itemviews/spreadsheet/spreadsheetitem.h | 7 ++- 8 files changed, 53 insertions(+), 71 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/itemviews/spreadsheet/main.cpp b/examples/widgets/itemviews/spreadsheet/main.cpp index 769edbdf03..548dc8d604 100644 --- a/examples/widgets/itemviews/spreadsheet/main.cpp +++ b/examples/widgets/itemviews/spreadsheet/main.cpp @@ -53,7 +53,8 @@ #include #include -int main(int argc, char** argv) { +int main(int argc, char **argv) +{ Q_INIT_RESOURCE(spreadsheet); QApplication app(argc, argv); SpreadSheet sheet(10, 6); diff --git a/examples/widgets/itemviews/spreadsheet/printview.cpp b/examples/widgets/itemviews/spreadsheet/printview.cpp index 31424e9070..7db1a6bad9 100644 --- a/examples/widgets/itemviews/spreadsheet/printview.cpp +++ b/examples/widgets/itemviews/spreadsheet/printview.cpp @@ -48,12 +48,11 @@ ** ****************************************************************************/ +#include "printview.h" + #ifndef QT_NO_PRINTER #include #endif -#include - -#include "printview.h" PrintView::PrintView() { diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp index 621f655b02..421b4a240c 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp @@ -48,36 +48,30 @@ ** ****************************************************************************/ -#include -#if defined(QT_PRINTSUPPORT_LIB) -#include -#if QT_CONFIG(printdialog) -#include -#include -#endif -#if QT_CONFIG(printpreviewdialog) -#include -#endif -#endif - #include "spreadsheet.h" #include "spreadsheetdelegate.h" #include "spreadsheetitem.h" #include "printview.h" +#include +#if defined(QT_PRINTSUPPORT_LIB) +#include +#endif + SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent) - : QMainWindow(parent) + : QMainWindow(parent), + toolBar(new QToolBar(this)), + cellLabel(new QLabel(toolBar)), + table(new QTableWidget(rows, cols, this)), + formulaInput(new QLineEdit(this)) { - addToolBar(toolBar = new QToolBar()); - formulaInput = new QLineEdit(); + addToolBar(toolBar); - cellLabel = new QLabel(toolBar); cellLabel->setMinimumSize(80, 0); toolBar->addWidget(cellLabel); toolBar->addWidget(formulaInput); - table = new QTableWidget(rows, cols, this); table->setSizeAdjustPolicy(QTableWidget::AdjustToContents); for (int c = 0; c < cols; ++c) { QString character(QChar('A' + c)); @@ -88,7 +82,7 @@ SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent) table->setItemDelegate(new SpreadSheetDelegate()); createActions(); - updateColor(0); + updateColor(nullptr); setupMenuBar(); setupContents(); setupContextMenu(); @@ -103,7 +97,8 @@ SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent) this, &SpreadSheet::updateLineEdit); connect(table, &QTableWidget::itemChanged, this, &SpreadSheet::updateStatus); - connect(formulaInput, &QLineEdit::returnPressed, this, &SpreadSheet::returnPressed); + connect(formulaInput, &QLineEdit::returnPressed, + this, &SpreadSheet::returnPressed); connect(table, &QTableWidget::itemChanged, this, &SpreadSheet::updateLineEdit); @@ -245,11 +240,11 @@ void SpreadSheet::selectColor() if (!col.isValid()) return; - QList selected = table->selectedItems(); - if (selected.count() == 0) + const QList selected = table->selectedItems(); + if (selected.isEmpty()) return; - foreach (QTableWidgetItem *i, selected) { + for (QTableWidgetItem *i : selected) { if (i) i->setBackgroundColor(col); } @@ -259,8 +254,8 @@ void SpreadSheet::selectColor() void SpreadSheet::selectFont() { - QList selected = table->selectedItems(); - if (selected.count() == 0) + const QList selected = table->selectedItems(); + if (selected.isEmpty()) return; bool ok = false; @@ -268,7 +263,7 @@ void SpreadSheet::selectFont() if (!ok) return; - foreach (QTableWidgetItem *i, selected) { + for (QTableWidgetItem *i : selected) { if (i) i->setFont(fnt); } @@ -397,7 +392,7 @@ void SpreadSheet::actionSum() int col_last = 0; int col_cur = 0; - QList selected = table->selectedItems(); + const QList selected = table->selectedItems(); if (!selected.isEmpty()) { QTableWidgetItem *first = selected.first(); @@ -408,7 +403,7 @@ void SpreadSheet::actionSum() col_last = table->column(last); } - QTableWidgetItem *current = table->currentItem(); + const QTableWidgetItem *current = table->currentItem(); if (current) { row_cur = table->row(current); @@ -435,7 +430,7 @@ void SpreadSheet::actionMath_helper(const QString &title, const QString &op) QString cell2 = "C2"; QString out = "C3"; - QTableWidgetItem *current = table->currentItem(); + const QTableWidgetItem *current = table->currentItem(); if (current) out = encode_pos(table->currentRow(), table->currentColumn()); @@ -468,8 +463,9 @@ void SpreadSheet::actionDivide() void SpreadSheet::clear() { - foreach (QTableWidgetItem *i, table->selectedItems()) - i->setText(""); + const QList selectedItems = table->selectedItems(); + for (QTableWidgetItem *i : selectedItems) + i->setText(QString()); } void SpreadSheet::setupContextMenu() diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.h b/examples/widgets/itemviews/spreadsheet/spreadsheet.h index a90d1d8c20..b36a377156 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheet.h +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.h @@ -65,10 +65,8 @@ QT_END_NAMESPACE class SpreadSheet : public QMainWindow { Q_OBJECT - public: - - SpreadSheet(int rows, int cols, QWidget *parent = 0); + SpreadSheet(int rows, int cols, QWidget *parent = nullptr); public slots: void updateStatus(QTableWidgetItem *item); diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp index aaf8902af5..eadd5fadb8 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp @@ -53,11 +53,12 @@ #include SpreadSheetDelegate::SpreadSheetDelegate(QObject *parent) - : QItemDelegate(parent) {} + : QItemDelegate(parent) +{} QWidget *SpreadSheetDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &, - const QModelIndex &index) const + const QStyleOptionViewItem &, + const QModelIndex &index) const { if (index.column() == 1) { QDateTimeEdit *editor = new QDateTimeEdit(parent); @@ -92,7 +93,7 @@ void SpreadSheetDelegate::commitAndCloseEditor() } void SpreadSheetDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const + const QModelIndex &index) const { QLineEdit *edit = qobject_cast(editor); if (edit) { @@ -109,7 +110,8 @@ void SpreadSheetDelegate::setEditorData(QWidget *editor, } void SpreadSheetDelegate::setModelData(QWidget *editor, - QAbstractItemModel *model, const QModelIndex &index) const + QAbstractItemModel *model, + const QModelIndex &index) const { QLineEdit *edit = qobject_cast(editor); if (edit) { diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h index 333467720f..c89459cadf 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h @@ -51,8 +51,6 @@ #ifndef SPREADSHEETDELEGATE_H #define SPREADSHEETDELEGATE_H -#include "spreadsheet.h" - #include class SpreadSheetDelegate : public QItemDelegate @@ -60,7 +58,7 @@ class SpreadSheetDelegate : public QItemDelegate Q_OBJECT public: - SpreadSheetDelegate(QObject *parent = 0); + SpreadSheetDelegate(QObject *parent = nullptr); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp index 92cbaff031..62d3a6fdcd 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp @@ -50,19 +50,9 @@ #include "spreadsheetitem.h" -SpreadSheetItem::SpreadSheetItem() - : QTableWidgetItem(), isResolving(false) -{ -} - -SpreadSheetItem::SpreadSheetItem(const QString &text) - : QTableWidgetItem(text), isResolving(false) -{ -} - QTableWidgetItem *SpreadSheetItem::clone() const { - SpreadSheetItem *item = new SpreadSheetItem(); + SpreadSheetItem *item = new SpreadSheetItem; *item = *this; return item; } @@ -75,21 +65,20 @@ QVariant SpreadSheetItem::data(int role) const if (role == Qt::DisplayRole) return display(); - QString t = display().toString(); - bool isNumber = false; - int number = t.toInt(&isNumber); + const QString t = display().toString(); if (role == Qt::ForegroundRole) { - if (!isNumber) - return QVariant::fromValue(QColor(Qt::black)); - else if (number < 0) - return QVariant::fromValue(QColor(Qt::red)); - return QVariant::fromValue(QColor(Qt::blue)); + bool isNumber = false; + const int number = t.toInt(&isNumber); + QColor color = Qt::black; + if (isNumber) + color = (number < 0) ? Qt::red : Qt::blue; + return QVariant::fromValue(color); } - if (role == Qt::TextAlignmentRole) - if (!t.isEmpty() && (t.at(0).isNumber() || t.at(0) == '-')) - return (int)(Qt::AlignRight | Qt::AlignVCenter); + if (role == Qt::TextAlignmentRole) + if (!t.isEmpty() && (t.at(0).isNumber() || t.at(0) == '-')) + return int(Qt::AlignRight | Qt::AlignVCenter); return QTableWidgetItem::data(role); } diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h index 46460df527..159f4a7eea 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h @@ -58,8 +58,7 @@ class SpreadSheetItem : public QTableWidgetItem { public: - SpreadSheetItem(); - SpreadSheetItem(const QString &text); + using QTableWidgetItem::QTableWidgetItem; QTableWidgetItem *clone() const override; @@ -74,10 +73,10 @@ public: static QVariant computeFormula(const QString &formula, const QTableWidget *widget, - const QTableWidgetItem *self = 0); + const QTableWidgetItem *self = nullptr); private: - mutable bool isResolving; + mutable bool isResolving = false; }; #endif // SPREADSHEETITEM_H -- cgit v1.2.3 From 7aaf54f5725c65bf830088a9cfd104ef4817f256 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Mon, 12 Nov 2018 15:18:12 +0100 Subject: Codecs example: Add a dialog for showing common C++ encodings Add a dialog where the user can enter a line of text, which is then displayed in several encodings with special characters converted suitable for C++/Python string literals. Task-number: QTBUG-60635 Change-Id: Ibd436f9f76e128c93cbb581235c730d636641d8a Reviewed-by: Andy Shaw --- examples/widgets/tools/codecs/codecs.pro | 9 +- examples/widgets/tools/codecs/codecs.qrc | 5 + examples/widgets/tools/codecs/encodingdialog.cpp | 333 ++++++++++++++++++++++ examples/widgets/tools/codecs/encodingdialog.h | 73 +++++ examples/widgets/tools/codecs/images/editcopy.png | Bin 0 -> 1325 bytes examples/widgets/tools/codecs/mainwindow.cpp | 19 ++ examples/widgets/tools/codecs/mainwindow.h | 4 + 7 files changed, 441 insertions(+), 2 deletions(-) create mode 100644 examples/widgets/tools/codecs/codecs.qrc create mode 100644 examples/widgets/tools/codecs/encodingdialog.cpp create mode 100644 examples/widgets/tools/codecs/encodingdialog.h create mode 100644 examples/widgets/tools/codecs/images/editcopy.png (limited to 'examples/widgets') diff --git a/examples/widgets/tools/codecs/codecs.pro b/examples/widgets/tools/codecs/codecs.pro index 13daa79237..6f4b0742a9 100644 --- a/examples/widgets/tools/codecs/codecs.pro +++ b/examples/widgets/tools/codecs/codecs.pro @@ -2,10 +2,15 @@ QT += widgets requires(qtConfig(filedialog)) HEADERS += mainwindow.h \ - previewform.h + previewform.h \ + encodingdialog.h + SOURCES += main.cpp \ mainwindow.cpp \ - previewform.cpp + previewform.cpp \ + encodingdialog.cpp + +RESOURCES += codecs.qrc EXAMPLE_FILES = encodedfiles diff --git a/examples/widgets/tools/codecs/codecs.qrc b/examples/widgets/tools/codecs/codecs.qrc new file mode 100644 index 0000000000..65fa1aa64d --- /dev/null +++ b/examples/widgets/tools/codecs/codecs.qrc @@ -0,0 +1,5 @@ + + + images/editcopy.png + + diff --git a/examples/widgets/tools/codecs/encodingdialog.cpp b/examples/widgets/tools/codecs/encodingdialog.cpp new file mode 100644 index 0000000000..ca4b56db9e --- /dev/null +++ b/examples/widgets/tools/codecs/encodingdialog.cpp @@ -0,0 +1,333 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "encodingdialog.h" + +#if QT_CONFIG(action) +# include +#endif +#include +#include +#include +#include +#include + +#if QT_CONFIG(clipboard) +# include +# include +#endif + +#include + +// Helpers for formatting character sequences + +// Format a special character like '\x0a' +template +static void formatEscapedNumber(QTextStream &str, Int value, int base, + int width = 0,char prefix = 0) +{ + str << '\\'; + if (prefix) + str << prefix; + const auto oldPadChar = str.padChar(); + const auto oldFieldWidth = str.fieldWidth(); + const auto oldFieldAlignment = str.fieldAlignment(); + const auto oldIntegerBase = str.integerBase(); + str.setPadChar(QLatin1Char('0')); + str.setFieldWidth(width); + str.setFieldAlignment(QTextStream::AlignRight); + str.setIntegerBase(base); + str << value; + str.setIntegerBase(oldIntegerBase); + str.setFieldAlignment(oldFieldAlignment); + str.setFieldWidth(oldFieldWidth); + str.setPadChar(oldPadChar); +} + +template +static bool formatSpecialCharacter(QTextStream &str, Int value) +{ + bool result = true; + switch (value) { + case '\\': + str << "\\\\"; + break; + case '\"': + str << "\\\""; + break; + case '\n': + str << "\\n"; + break; + default: + result = false; + break; + } + return result; +} + +// Format a sequence of characters (QChar, ushort (UTF-16), uint (UTF-32) +// or just char (Latin1, Utf-8)) with the help of traits specifying +// how to obtain the code for checking the printable-ness and how to +// stream out the plain ASCII values. + +template +struct FormattingTraits +{ +}; + +template <> +struct FormattingTraits +{ + static ushort code(QChar c) { return c.unicode(); } + static char toAscii(QChar c) { return c.toLatin1(); } +}; + +template <> +struct FormattingTraits +{ + static ushort code(char c) { return uchar(c); } + static char toAscii(char c) { return c; } +}; + +template <> +struct FormattingTraits +{ + static ushort code(ushort c) { return c; } + static char toAscii(ushort c) { return char(c); } +}; + +template <> +struct FormattingTraits +{ + static uint code(uint c) { return c; } + static char toAscii(uint c) { return char(c); } +}; + +template <> +struct FormattingTraits +{ + static uchar code(char c) { return uchar(c); } + static char toAscii(char c) { return c; } +}; + +static bool isHexDigit(char c) +{ + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') + || (c >= 'A' && c <= 'F'); +} + +template +static void formatStringSequence(QTextStream &str, Iterator i1, Iterator i2, + int escapeIntegerBase, int escapeWidth, + char escapePrefix = 0) +{ + str << '"'; + bool separateHexEscape = false; + for (; i1 != i2; ++i1) { + const auto code = FormattingTraits::code(*i1); + if (code >= 0x80) { + formatEscapedNumber(str, code, escapeIntegerBase, escapeWidth, escapePrefix); + separateHexEscape = escapeIntegerBase == 16 && escapeWidth == 0; + } else { + if (!formatSpecialCharacter(str, code)) { + const char c = FormattingTraits::toAscii(*i1); + // For variable width/hex: Terminate the literal to stop digit parsing + // ("\x12" "34..."). + if (separateHexEscape && isHexDigit(c)) + str << "\" \""; + str << c; + } + separateHexEscape = false; + } + } + str << '"'; +} + +static QString encodedString(const QString &value, EncodingDialog::Encoding e) +{ + QString result; + QTextStream str(&result); + switch (e) { + case EncodingDialog::Unicode: + formatStringSequence(str, value.cbegin(), value.cend(), + 16, 4, 'u'); + break; + case EncodingDialog::Utf8: { + const QByteArray utf8 = value.toUtf8(); + str << "u8"; + formatStringSequence(str, utf8.cbegin(), utf8.cend(), + 8, 3); + } + break; + case EncodingDialog::Utf16: { + auto utf16 = value.utf16(); + auto utf16End = utf16 + value.size(); + str << 'u'; + formatStringSequence(str, utf16, utf16End, + 16, 0, 'x'); + } + break; + case EncodingDialog::Utf32: { + auto utf32 = value.toUcs4(); + str << 'U'; + formatStringSequence(str, utf32.cbegin(), utf32.cend(), + 16, 0, 'x'); + } + break; + case EncodingDialog::Latin1: { + const QByteArray latin1 = value.toLatin1(); + formatStringSequence(str, latin1.cbegin(), latin1.cend(), + 16, 0, 'x'); + } + break; + case EncodingDialog::EncodingCount: + break; + } + return result; +} + +// Dialog helpers + +static const char *encodingLabels[] +{ + QT_TRANSLATE_NOOP("EncodingDialog", "Unicode:"), + QT_TRANSLATE_NOOP("EncodingDialog", "UTF-8:"), + QT_TRANSLATE_NOOP("EncodingDialog", "UTF-16:"), + QT_TRANSLATE_NOOP("EncodingDialog", "UTF-32:"), + QT_TRANSLATE_NOOP("EncodingDialog", "Latin1:") +}; + +static const char *encodingToolTips[] +{ + QT_TRANSLATE_NOOP("EncodingDialog", "Unicode points for use with any encoding (C++, Python)"), + QT_TRANSLATE_NOOP("EncodingDialog", "QString::fromUtf8()"), + QT_TRANSLATE_NOOP("EncodingDialog", "QStringViewLiteral(), wchar_t on Windows"), + QT_TRANSLATE_NOOP("EncodingDialog", "wchar_t on Unix (Ucs4)"), + QT_TRANSLATE_NOOP("EncodingDialog", "QLatin1String") +}; + +// A read-only line edit with a tool button to copy the contents +class DisplayLineEdit : public QLineEdit +{ + Q_OBJECT +public: + explicit DisplayLineEdit(const QIcon &icon, QWidget *parent = nullptr); + +public slots: + void copyAll(); +}; + +DisplayLineEdit::DisplayLineEdit(const QIcon &icon, QWidget *parent) : + QLineEdit(parent) +{ + setReadOnly(true); +#if QT_CONFIG(clipboard) && QT_CONFIG(action) + auto copyAction = addAction(icon, QLineEdit::TrailingPosition); + connect(copyAction, &QAction::triggered, this, &DisplayLineEdit::copyAll); +#endif +} + +void DisplayLineEdit::copyAll() +{ +#if QT_CONFIG(clipboard) + QGuiApplication::clipboard()->setText(text()); +#endif +} + +static void addFormLayoutRow(QFormLayout *formLayout, const QString &text, + QWidget *w, const QString &toolTip) +{ + auto label = new QLabel(text); + label->setToolTip(toolTip); + w->setToolTip(toolTip); + label->setBuddy(w); + formLayout->addRow(label, w); +} + +EncodingDialog::EncodingDialog(QWidget *parent) : + QDialog(parent) +{ + setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); + setWindowTitle(tr("Encodings")); + + auto formLayout = new QFormLayout; + auto sourceLineEdit = new QLineEdit(this); + sourceLineEdit->setClearButtonEnabled(true); + connect(sourceLineEdit, &QLineEdit::textChanged, this, &EncodingDialog::textChanged); + + addFormLayoutRow(formLayout, tr("&Source:"), sourceLineEdit, tr("Enter text")); + + const auto copyIcon = QIcon::fromTheme(QLatin1String("edit-copy"), + QIcon(QLatin1String(":/images/editcopy"))); + for (int i = 0; i < EncodingCount; ++i) { + m_lineEdits[i] = new DisplayLineEdit(copyIcon, this); + addFormLayoutRow(formLayout, tr(encodingLabels[i]), + m_lineEdits[i], tr(encodingToolTips[i])); + } + + auto mainLayout = new QVBoxLayout(this); + mainLayout->addLayout(formLayout); + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + mainLayout->addWidget(buttonBox); +} + +void EncodingDialog::textChanged(const QString &t) +{ + if (t.isEmpty()) { + for (auto lineEdit : m_lineEdits) + lineEdit->clear(); + } else { + for (int i = 0; i < EncodingCount; ++i) + m_lineEdits[i]->setText(encodedString(t, static_cast(i))); + } +} + +#include "encodingdialog.moc" diff --git a/examples/widgets/tools/codecs/encodingdialog.h b/examples/widgets/tools/codecs/encodingdialog.h new file mode 100644 index 0000000000..3f82da84af --- /dev/null +++ b/examples/widgets/tools/codecs/encodingdialog.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ENCODINGDIALOG_H +#define ENCODINGDIALOG_H + +#include + +QT_FORWARD_DECLARE_CLASS(QLineEdit) + +class EncodingDialog : public QDialog +{ + Q_OBJECT +public: + explicit EncodingDialog(QWidget *parent = nullptr); + + enum Encoding { Unicode, Utf8, Utf16, Utf32, Latin1, EncodingCount }; + +private slots: + void textChanged(const QString &t); + +private: + QLineEdit *m_lineEdits[EncodingCount]; +}; + +#endif // ENCODINGDIALOG_H diff --git a/examples/widgets/tools/codecs/images/editcopy.png b/examples/widgets/tools/codecs/images/editcopy.png new file mode 100644 index 0000000000..1121b47d8b Binary files /dev/null and b/examples/widgets/tools/codecs/images/editcopy.png differ diff --git a/examples/widgets/tools/codecs/mainwindow.cpp b/examples/widgets/tools/codecs/mainwindow.cpp index 28f904d1a7..229c2ccfd4 100644 --- a/examples/widgets/tools/codecs/mainwindow.cpp +++ b/examples/widgets/tools/codecs/mainwindow.cpp @@ -51,6 +51,7 @@ #include #include "mainwindow.h" +#include "encodingdialog.h" #include "previewform.h" MainWindow::MainWindow() @@ -188,9 +189,27 @@ void MainWindow::createMenus() QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); + auto toolMenu = menuBar()->addMenu(tr("&Tools")); + auto encodingAction = toolMenu->addAction(tr("Encodings"), this, &MainWindow::encodingDialog); + encodingAction->setShortcut(Qt::CTRL + Qt::Key_E); + encodingAction->setToolTip(tr("Shows a dialog allowing to convert to common encoding in programming languages.")); + + menuBar()->addSeparator(); QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(tr("&About"), this, &MainWindow::about); helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); } + +void MainWindow::encodingDialog() +{ + if (!m_encodingDialog) { + m_encodingDialog = new EncodingDialog(this); + const QRect screenGeometry = QApplication::desktop()->screenGeometry(this); + m_encodingDialog->setMinimumWidth(screenGeometry.width() / 4); + } + m_encodingDialog->show(); + m_encodingDialog->raise(); + +} diff --git a/examples/widgets/tools/codecs/mainwindow.h b/examples/widgets/tools/codecs/mainwindow.h index 7121c0b122..64494d1960 100644 --- a/examples/widgets/tools/codecs/mainwindow.h +++ b/examples/widgets/tools/codecs/mainwindow.h @@ -59,6 +59,8 @@ class QAction; class QTextCodec; class QPlainTextEdit; QT_END_NAMESPACE + +class EncodingDialog; class PreviewForm; class MainWindow : public QMainWindow @@ -73,6 +75,7 @@ private slots: void save(); void about(); void aboutToShowSaveAsMenu(); + void encodingDialog(); private: void findCodecs(); @@ -82,6 +85,7 @@ private: QPlainTextEdit *textEdit; PreviewForm *previewForm; QList codecs; + EncodingDialog *m_encodingDialog = nullptr; }; #endif -- cgit v1.2.3 From 51f6d5d8c261fb94adc9bf5754cabf8e37236af5 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Mon, 12 Nov 2018 21:20:34 +0100 Subject: Cleanup Addressbook example Cleanup the Addressbook example: - use nullptr - use for instead foreach - don't use public members but setters/getters - use QVector instead QList - make user-visible translatable Change-Id: Ie7bdad8a2799c8fa6f634659b51c3064cc8a04ce Reviewed-by: Samuel Gaist Reviewed-by: Sze Howe Koh Reviewed-by: Paul Wicking Reviewed-by: Luca Beldi --- examples/widgets/doc/src/addressbook.qdoc | 11 ++-- .../widgets/itemviews/addressbook/adddialog.cpp | 38 ++++++++---- examples/widgets/itemviews/addressbook/adddialog.h | 14 ++--- .../itemviews/addressbook/addresswidget.cpp | 69 +++++++++------------- .../widgets/itemviews/addressbook/addresswidget.h | 5 +- .../widgets/itemviews/addressbook/mainwindow.cpp | 18 +++--- .../widgets/itemviews/addressbook/mainwindow.h | 6 -- .../itemviews/addressbook/newaddresstab.cpp | 21 +++---- .../widgets/itemviews/addressbook/newaddresstab.h | 10 +--- .../widgets/itemviews/addressbook/tablemodel.cpp | 52 ++++++++-------- .../widgets/itemviews/addressbook/tablemodel.h | 10 ++-- 11 files changed, 120 insertions(+), 134 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/doc/src/addressbook.qdoc b/examples/widgets/doc/src/addressbook.qdoc index 1fa0bfa9d4..e5e7fe5c2c 100644 --- a/examples/widgets/doc/src/addressbook.qdoc +++ b/examples/widgets/doc/src/addressbook.qdoc @@ -90,8 +90,8 @@ \snippet itemviews/addressbook/tablemodel.h 0 Two constructors are used, a default constructor which uses - \c TableModel's own \c {QList} and one that takes - \c {QList} as an argument, for convenience. + \c TableModel's own \c {QVector} and one that takes + \c {QVector} as an argument, for convenience. \section1 TableModel Class Implementation @@ -108,9 +108,6 @@ \c columnCount()'s value is always 2 because we only need space for the \b Name and \b Address columns. - \note The \c Q_UNUSED() macro prevents the compiler from - generating warnings regarding unused parameters. - \snippet itemviews/addressbook/tablemodel.cpp 1 The \c data() function returns either a \b Name or @@ -164,7 +161,7 @@ them here so that we can reuse the model in other programs. The last function in \c {TableModel}, \c getContacts() returns the - QList object that holds all the contacts in the address + QVector object that holds all the contacts in the address book. We use this function later to obtain the list of contacts to check for existing entries, write the contacts to a file and read them back. Further explanation is given with \c AddressWidget. @@ -233,7 +230,7 @@ \image addressbook-signals.png Signals and Slots Connections - We provide 2 \c addEntry() functions: 1 which is intended to be + We provide two \c addEntry() functions: One which is intended to be used to accept user input, and the other which performs the actual task of adding new entries to the address book. We divide the responsibility of adding entries into two parts to allow diff --git a/examples/widgets/itemviews/addressbook/adddialog.cpp b/examples/widgets/itemviews/addressbook/adddialog.cpp index 1ce2d3110a..bf87307253 100644 --- a/examples/widgets/itemviews/addressbook/adddialog.cpp +++ b/examples/widgets/itemviews/addressbook/adddialog.cpp @@ -54,17 +54,16 @@ //! [0] AddDialog::AddDialog(QWidget *parent) - : QDialog(parent) + : QDialog(parent), + nameText(new QLineEdit), + addressText(new QTextEdit) { - nameLabel = new QLabel("Name"); - addressLabel = new QLabel("Address"); - okButton = new QPushButton("OK"); - cancelButton = new QPushButton("Cancel"); + auto nameLabel = new QLabel(tr("Name")); + auto addressLabel = new QLabel(tr("Address")); + auto okButton = new QPushButton(tr("OK")); + auto cancelButton = new QPushButton(tr("Cancel")); - nameText = new QLineEdit; - addressText = new QTextEdit; - - QGridLayout *gLayout = new QGridLayout; + auto gLayout = new QGridLayout; gLayout->setColumnStretch(1, 2); gLayout->addWidget(nameLabel, 0, 0); gLayout->addWidget(nameText, 0, 1); @@ -72,13 +71,13 @@ AddDialog::AddDialog(QWidget *parent) gLayout->addWidget(addressLabel, 1, 0, Qt::AlignLeft|Qt::AlignTop); gLayout->addWidget(addressText, 1, 1, Qt::AlignLeft); - QHBoxLayout *buttonLayout = new QHBoxLayout; + auto buttonLayout = new QHBoxLayout; buttonLayout->addWidget(okButton); buttonLayout->addWidget(cancelButton); gLayout->addLayout(buttonLayout, 2, 1, Qt::AlignRight); - QVBoxLayout *mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addLayout(gLayout); setLayout(mainLayout); @@ -87,4 +86,21 @@ AddDialog::AddDialog(QWidget *parent) setWindowTitle(tr("Add a Contact")); } + +QString AddDialog::name() const +{ + return nameText->text(); +} + +QString AddDialog::address() const +{ + return addressText->toPlainText(); +} + +void AddDialog::editAddress(const QString &name, const QString &address) +{ + nameText->setReadOnly(true); + nameText->setText(name); + addressText->setPlainText(address); +} //! [0] diff --git a/examples/widgets/itemviews/addressbook/adddialog.h b/examples/widgets/itemviews/addressbook/adddialog.h index 16fa7bc650..2867034122 100644 --- a/examples/widgets/itemviews/addressbook/adddialog.h +++ b/examples/widgets/itemviews/addressbook/adddialog.h @@ -66,15 +66,15 @@ class AddDialog : public QDialog Q_OBJECT public: - AddDialog(QWidget *parent = 0); - QLineEdit *nameText; - QTextEdit *addressText; + AddDialog(QWidget *parent = nullptr); + + QString name() const; + QString address() const; + void editAddress(const QString &name, const QString &address); private: - QLabel *nameLabel; - QLabel *addressLabel; - QPushButton *okButton; - QPushButton *cancelButton; + QLineEdit *nameText; + QTextEdit *addressText; }; //! [0] diff --git a/examples/widgets/itemviews/addressbook/addresswidget.cpp b/examples/widgets/itemviews/addressbook/addresswidget.cpp index 143f6266dd..b1b65174ee 100644 --- a/examples/widgets/itemviews/addressbook/addresswidget.cpp +++ b/examples/widgets/itemviews/addressbook/addresswidget.cpp @@ -48,21 +48,21 @@ ** ****************************************************************************/ -#include "adddialog.h" #include "addresswidget.h" +#include "adddialog.h" #include //! [0] AddressWidget::AddressWidget(QWidget *parent) - : QTabWidget(parent) + : QTabWidget(parent), + table(new TableModel(this)), + newAddressTab(new NewAddressTab(this)) { - table = new TableModel(this); - newAddressTab = new NewAddressTab(this); connect(newAddressTab, &NewAddressTab::sendDetails, this, &AddressWidget::addEntry); - addTab(newAddressTab, "Address Book"); + addTab(newAddressTab, tr("Address Book")); setupTabs(); } @@ -73,17 +73,13 @@ void AddressWidget::showAddEntryDialog() { AddDialog aDialog; - if (aDialog.exec()) { - QString name = aDialog.nameText->text(); - QString address = aDialog.addressText->toPlainText(); - - addEntry(name, address); - } + if (aDialog.exec()) + addEntry(aDialog.name(), aDialog.address()); } //! [2] //! [3] -void AddressWidget::addEntry(QString name, QString address) +void AddressWidget::addEntry(const QString &name, const QString &address) { if (!table->getContacts().contains({ name, address })) { table->insertRows(0, 1, QModelIndex()); @@ -107,12 +103,12 @@ void AddressWidget::editEntry() QSortFilterProxyModel *proxy = static_cast(temp->model()); QItemSelectionModel *selectionModel = temp->selectionModel(); - QModelIndexList indexes = selectionModel->selectedRows(); + const QModelIndexList indexes = selectionModel->selectedRows(); QString name; QString address; int row = -1; - foreach (QModelIndex index, indexes) { + for (const QModelIndex &index : indexes) { row = proxy->mapToSource(index).row(); QModelIndex nameIndex = table->index(row, 0, QModelIndex()); QVariant varName = table->data(nameIndex, Qt::DisplayRole); @@ -127,15 +123,12 @@ void AddressWidget::editEntry() //! [4b] AddDialog aDialog; aDialog.setWindowTitle(tr("Edit a Contact")); - - aDialog.nameText->setReadOnly(true); - aDialog.nameText->setText(name); - aDialog.addressText->setText(address); + aDialog.editAddress(name, address); if (aDialog.exec()) { - QString newAddress = aDialog.addressText->toPlainText(); + const QString newAddress = aDialog.address(); if (newAddress != address) { - QModelIndex index = table->index(row, 1, QModelIndex()); + const QModelIndex index = table->index(row, 1, QModelIndex()); table->setData(index, newAddress, Qt::EditRole); } } @@ -149,52 +142,46 @@ void AddressWidget::removeEntry() QSortFilterProxyModel *proxy = static_cast(temp->model()); QItemSelectionModel *selectionModel = temp->selectionModel(); - QModelIndexList indexes = selectionModel->selectedRows(); + const QModelIndexList indexes = selectionModel->selectedRows(); - foreach (QModelIndex index, indexes) { + for (QModelIndex index : indexes) { int row = proxy->mapToSource(index).row(); table->removeRows(row, 1, QModelIndex()); } - if (table->rowCount(QModelIndex()) == 0) { - insertTab(0, newAddressTab, "Address Book"); - } + if (table->rowCount(QModelIndex()) == 0) + insertTab(0, newAddressTab, tr("Address Book")); } //! [5] //! [1] void AddressWidget::setupTabs() { - QStringList groups; - groups << "ABC" << "DEF" << "GHI" << "JKL" << "MNO" << "PQR" << "STU" << "VW" << "XYZ"; + const auto groups = { "ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VW", "XYZ" }; - for (int i = 0; i < groups.size(); ++i) { - QString str = groups.at(i); - QString regExp = QString("^[%1].*").arg(str); + for (const QString &str : groups) { + const auto regExp = QRegularExpression(QString("^[%1].*").arg(str), + QRegularExpression::CaseInsensitiveOption); - proxyModel = new QSortFilterProxyModel(this); + auto proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(table); - proxyModel->setFilterRegExp(QRegExp(regExp, Qt::CaseInsensitive)); + proxyModel->setFilterRegularExpression(regExp); proxyModel->setFilterKeyColumn(0); QTableView *tableView = new QTableView; tableView->setModel(proxyModel); - tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->horizontalHeader()->setStretchLastSection(true); tableView->verticalHeader()->hide(); tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); tableView->setSelectionMode(QAbstractItemView::SingleSelection); - tableView->setSortingEnabled(true); - connect(tableView->selectionModel(), - &QItemSelectionModel::selectionChanged, - this, &AddressWidget::selectionChanged); + connect(tableView->selectionModel(), &QItemSelectionModel::selectionChanged, + this, &AddressWidget::selectionChanged); - connect(this, &QTabWidget::currentChanged, this, [this](int tabIndex) { - auto *tableView = qobject_cast(widget(tabIndex)); - if (tableView) + connect(this, &QTabWidget::currentChanged, this, [this, tableView](int tabIndex) { + if (widget(tabIndex) == tableView) emit selectionChanged(tableView->selectionModel()->selection()); }); @@ -214,7 +201,7 @@ void AddressWidget::readFromFile(const QString &fileName) return; } - QList contacts; + QVector contacts; QDataStream in(&file); in >> contacts; diff --git a/examples/widgets/itemviews/addressbook/addresswidget.h b/examples/widgets/itemviews/addressbook/addresswidget.h index de5a2da766..111ea98328 100644 --- a/examples/widgets/itemviews/addressbook/addresswidget.h +++ b/examples/widgets/itemviews/addressbook/addresswidget.h @@ -68,13 +68,13 @@ class AddressWidget : public QTabWidget Q_OBJECT public: - AddressWidget(QWidget *parent = 0); + AddressWidget(QWidget *parent = nullptr); void readFromFile(const QString &fileName); void writeToFile(const QString &fileName); public slots: void showAddEntryDialog(); - void addEntry(QString name, QString address); + void addEntry(const QString &name, const QString &address); void editEntry(); void removeEntry(); @@ -86,7 +86,6 @@ private: TableModel *table; NewAddressTab *newAddressTab; - QSortFilterProxyModel *proxyModel; }; //! [0] diff --git a/examples/widgets/itemviews/addressbook/mainwindow.cpp b/examples/widgets/itemviews/addressbook/mainwindow.cpp index 6d8b15b032..42966de375 100644 --- a/examples/widgets/itemviews/addressbook/mainwindow.cpp +++ b/examples/widgets/itemviews/addressbook/mainwindow.cpp @@ -56,8 +56,9 @@ //! [0] MainWindow::MainWindow() + : QMainWindow(), + addressWidget(new AddressWidget) { - addressWidget = new AddressWidget; setCentralWidget(addressWidget); createMenus(); setWindowTitle(tr("Address Book")); @@ -67,28 +68,29 @@ MainWindow::MainWindow() //! [1a] void MainWindow::createMenus() { - fileMenu = menuBar()->addMenu(tr("&File")); + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); - openAct = new QAction(tr("&Open..."), this); + QAction *openAct = new QAction(tr("&Open..."), this); fileMenu->addAction(openAct); connect(openAct, &QAction::triggered, this, &MainWindow::openFile); //! [1a] - saveAct = new QAction(tr("&Save As..."), this); + QAction *saveAct = new QAction(tr("&Save As..."), this); fileMenu->addAction(saveAct); connect(saveAct, &QAction::triggered, this, &MainWindow::saveFile); fileMenu->addSeparator(); - exitAct = new QAction(tr("E&xit"), this); + QAction *exitAct = new QAction(tr("E&xit"), this); fileMenu->addAction(exitAct); connect(exitAct, &QAction::triggered, this, &QWidget::close); - toolMenu = menuBar()->addMenu(tr("&Tools")); + QMenu *toolMenu = menuBar()->addMenu(tr("&Tools")); - addAct = new QAction(tr("&Add Entry..."), this); + QAction *addAct = new QAction(tr("&Add Entry..."), this); toolMenu->addAction(addAct); - connect(addAct, &QAction::triggered, addressWidget, &AddressWidget::showAddEntryDialog); + connect(addAct, &QAction::triggered, + addressWidget, &AddressWidget::showAddEntryDialog); //! [1b] editAct = new QAction(tr("&Edit Entry..."), this); diff --git a/examples/widgets/itemviews/addressbook/mainwindow.h b/examples/widgets/itemviews/addressbook/mainwindow.h index 3d323e5799..fca5934e68 100644 --- a/examples/widgets/itemviews/addressbook/mainwindow.h +++ b/examples/widgets/itemviews/addressbook/mainwindow.h @@ -72,12 +72,6 @@ private: void createMenus(); AddressWidget *addressWidget; - QMenu *fileMenu; - QMenu *toolMenu; - QAction *openAct; - QAction *saveAct; - QAction *exitAct; - QAction *addAct; QAction *editAct; QAction *removeAct; }; diff --git a/examples/widgets/itemviews/addressbook/newaddresstab.cpp b/examples/widgets/itemviews/addressbook/newaddresstab.cpp index f0a7369796..ef725d723f 100644 --- a/examples/widgets/itemviews/addressbook/newaddresstab.cpp +++ b/examples/widgets/itemviews/addressbook/newaddresstab.cpp @@ -48,24 +48,23 @@ ** ****************************************************************************/ -#include "adddialog.h" #include "newaddresstab.h" +#include "adddialog.h" #include //! [0] NewAddressTab::NewAddressTab(QWidget *parent) + : QWidget(parent) { - Q_UNUSED(parent); + auto descriptionLabel = new QLabel(tr("There are currently no contacts in your address book. " + "\nClick Add to add new contacts.")); - descriptionLabel = new QLabel(tr("There are currently no contacts in your address book. " - "\nClick Add to add new contacts.")); - - addButton = new QPushButton(tr("Add")); + auto addButton = new QPushButton(tr("Add")); connect(addButton, &QAbstractButton::clicked, this, &NewAddressTab::addEntry); - mainLayout = new QVBoxLayout; + auto mainLayout = new QVBoxLayout; mainLayout->addWidget(descriptionLabel); mainLayout->addWidget(addButton, 0, Qt::AlignCenter); @@ -78,11 +77,7 @@ void NewAddressTab::addEntry() { AddDialog aDialog; - if (aDialog.exec()) { - QString name = aDialog.nameText->text(); - QString address = aDialog.addressText->toPlainText(); - - emit sendDetails(name, address); - } + if (aDialog.exec()) + emit sendDetails(aDialog.name(), aDialog.address()); } //! [1] diff --git a/examples/widgets/itemviews/addressbook/newaddresstab.h b/examples/widgets/itemviews/addressbook/newaddresstab.h index 05c7a8dada..6a147e3c7c 100644 --- a/examples/widgets/itemviews/addressbook/newaddresstab.h +++ b/examples/widgets/itemviews/addressbook/newaddresstab.h @@ -65,19 +65,13 @@ class NewAddressTab : public QWidget Q_OBJECT public: - NewAddressTab(QWidget *parent = 0); + NewAddressTab(QWidget *parent = nullptr); public slots: void addEntry(); signals: - void sendDetails(QString name, QString address); - -private: - QLabel *descriptionLabel; - QPushButton *addButton; - QVBoxLayout *mainLayout; - + void sendDetails(const QString &name, const QString &address); }; //! [0] diff --git a/examples/widgets/itemviews/addressbook/tablemodel.cpp b/examples/widgets/itemviews/addressbook/tablemodel.cpp index b3704f857e..ddf79a3fa3 100644 --- a/examples/widgets/itemviews/addressbook/tablemodel.cpp +++ b/examples/widgets/itemviews/addressbook/tablemodel.cpp @@ -56,9 +56,9 @@ TableModel::TableModel(QObject *parent) { } -TableModel::TableModel(QList contacts, QObject *parent) - : QAbstractTableModel(parent) - , contacts(contacts) +TableModel::TableModel(const QVector &contacts, QObject *parent) + : QAbstractTableModel(parent), + contacts(contacts) { } //! [0] @@ -66,14 +66,12 @@ TableModel::TableModel(QList contacts, QObject *parent) //! [1] int TableModel::rowCount(const QModelIndex &parent) const { - Q_UNUSED(parent); - return contacts.size(); + return parent.isValid() ? 0 : contacts.size(); } int TableModel::columnCount(const QModelIndex &parent) const { - Q_UNUSED(parent); - return 2; + return parent.isValid() ? 0 : 2; } //! [1] @@ -89,10 +87,14 @@ QVariant TableModel::data(const QModelIndex &index, int role) const if (role == Qt::DisplayRole) { const auto &contact = contacts.at(index.row()); - if (index.column() == 0) - return contact.name; - else if (index.column() == 1) - return contact.address; + switch (index.column()) { + case 0: + return contact.name; + case 1: + return contact.address; + default: + break; + } } return QVariant(); } @@ -108,12 +110,10 @@ QVariant TableModel::headerData(int section, Qt::Orientation orientation, int ro switch (section) { case 0: return tr("Name"); - case 1: return tr("Address"); - default: - return QVariant(); + break; } } return QVariant(); @@ -152,19 +152,21 @@ bool TableModel::removeRows(int position, int rows, const QModelIndex &index) bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { - int row = index.row(); - + const int row = index.row(); auto contact = contacts.value(row); - if (index.column() == 0) - contact.name = value.toString(); - else if (index.column() == 1) - contact.address = value.toString(); - else - return false; - + switch (index.column()) { + case 0: + contact.name = value.toString(); + break; + case 1: + contact.address = value.toString(); + break; + default: + return false; + } contacts.replace(row, contact); - emit dataChanged(index, index, {role}); + emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole}); return true; } @@ -184,7 +186,7 @@ Qt::ItemFlags TableModel::flags(const QModelIndex &index) const //! [7] //! [8] -QList TableModel::getContacts() const +const QVector &TableModel::getContacts() const { return contacts; } diff --git a/examples/widgets/itemviews/addressbook/tablemodel.h b/examples/widgets/itemviews/addressbook/tablemodel.h index 1004a35d31..e4025fc734 100644 --- a/examples/widgets/itemviews/addressbook/tablemodel.h +++ b/examples/widgets/itemviews/addressbook/tablemodel.h @@ -52,7 +52,7 @@ #define TABLEMODEL_H #include -#include +#include //! [0] @@ -82,8 +82,8 @@ class TableModel : public QAbstractTableModel Q_OBJECT public: - TableModel(QObject *parent = 0); - TableModel(QList contacts, QObject *parent = 0); + TableModel(QObject *parent = nullptr); + TableModel(const QVector &contacts, QObject *parent = nullptr); int rowCount(const QModelIndex &parent) const override; int columnCount(const QModelIndex &parent) const override; @@ -93,10 +93,10 @@ public: bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; bool insertRows(int position, int rows, const QModelIndex &index = QModelIndex()) override; bool removeRows(int position, int rows, const QModelIndex &index = QModelIndex()) override; - QList getContacts() const; + const QVector &getContacts() const; private: - QList contacts; + QVector contacts; }; //! [0] -- cgit v1.2.3 From 1cfe064632099e036f964832c23afe266e54d59e Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Thu, 22 Nov 2018 21:21:25 +0100 Subject: Cleanup StarDelegate example Cleanup the StarDelegate example: - use QStyledItemDelegate instead QItemDelegate - use nullptr and other useful c++11 constructs - include the correct headers Change-Id: If2f65fe7cbdcdd4571d10ffa98d36eeab7836bbb Reviewed-by: Sze Howe Koh Reviewed-by: Paul Wicking Reviewed-by: Luca Beldi --- examples/widgets/doc/src/stardelegate.qdoc | 14 +++++------ examples/widgets/itemviews/stardelegate/main.cpp | 5 +--- .../itemviews/stardelegate/stardelegate.cpp | 8 +++---- .../widgets/itemviews/stardelegate/stardelegate.h | 3 +-- .../widgets/itemviews/stardelegate/stareditor.cpp | 20 ++++++++-------- .../widgets/itemviews/stardelegate/stareditor.h | 5 ++-- .../widgets/itemviews/stardelegate/starrating.cpp | 27 +++++++++------------- .../widgets/itemviews/stardelegate/starrating.h | 8 +++---- 8 files changed, 40 insertions(+), 50 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/doc/src/stardelegate.qdoc b/examples/widgets/doc/src/stardelegate.qdoc index 44d17662ca..0b91723a51 100644 --- a/examples/widgets/doc/src/stardelegate.qdoc +++ b/examples/widgets/doc/src/stardelegate.qdoc @@ -42,11 +42,11 @@ editing takes place. Delegates are subclasses of QAbstractItemDelegate. Qt provides - QItemDelegate, which inherits QAbstractItemDelegate and handles + QStyledItemDelegate, which inherits QAbstractItemDelegate and handles the most common data types (notably \c int and QString). If we need to support custom data types, or want to customize the rendering or the editing for existing data types, we can subclass - QAbstractItemDelegate or QItemDelegate. See \l{Delegate Classes} + QAbstractItemDelegate or QStyledItemDelegate. See \l{Delegate Classes} for more information about delegates, and \l{Model/View Programming} if you need a high-level introduction to Qt's model/view architecture (including delegates). @@ -62,9 +62,9 @@ expressed as stars, such as "2 out of 5 stars" or "5 out of 6 stars". - \li \c StarDelegate inherits QItemDelegate and provides support + \li \c StarDelegate inherits QStyledItemDelegate and provides support for \c StarRating (in addition to the data types already - handled by QItemDelegate). + handled by QStyledItemDelegate). \li \c StarEditor inherits QWidget and is used by \c StarDelegate to let the user edit a star rating using the mouse. @@ -80,12 +80,12 @@ \snippet itemviews/stardelegate/stardelegate.h 0 All public functions are reimplemented virtual functions from - QItemDelegate to provide custom rendering and editing. + QStyledItemDelegate to provide custom rendering and editing. \section1 StarDelegate Class Implementation The \l{QAbstractItemDelegate::}{paint()} function is - reimplemented from QItemDelegate and is called whenever the view + reimplemented from QStyledItemDelegate and is called whenever the view needs to repaint an item: \snippet itemviews/stardelegate/stardelegate.cpp 0 @@ -93,7 +93,7 @@ The function is invoked once for each item, represented by a QModelIndex object from the model. If the data stored in the item is a \c StarRating, we paint it ourselves; otherwise, we let - QItemDelegate paint it for us. This ensures that the \c + QStyledItemDelegate paint it for us. This ensures that the \c StarDelegate can handle the most common data types. If the item is a \c StarRating, we draw the background if the diff --git a/examples/widgets/itemviews/stardelegate/main.cpp b/examples/widgets/itemviews/stardelegate/main.cpp index 51ca30c73a..452976bba0 100644 --- a/examples/widgets/itemviews/stardelegate/main.cpp +++ b/examples/widgets/itemviews/stardelegate/main.cpp @@ -101,10 +101,7 @@ int main(int argc, char *argv[]) tableWidget.setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked); tableWidget.setSelectionBehavior(QAbstractItemView::SelectRows); - - QStringList headerLabels; - headerLabels << "Title" << "Genre" << "Artist" << "Rating"; - tableWidget.setHorizontalHeaderLabels(headerLabels); + tableWidget.setHorizontalHeaderLabels({"Title", "Genre", "Artist", "Rating"}); populateTableWidget(&tableWidget); diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.cpp b/examples/widgets/itemviews/stardelegate/stardelegate.cpp index da5902a160..41ae5a920f 100644 --- a/examples/widgets/itemviews/stardelegate/stardelegate.cpp +++ b/examples/widgets/itemviews/stardelegate/stardelegate.cpp @@ -65,7 +65,7 @@ void StarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, painter->fillRect(option.rect, option.palette.highlight()); starRating.paint(painter, option.rect, option.palette, - StarRating::ReadOnly); + StarRating::EditMode::ReadOnly); } else { QStyledItemDelegate::paint(painter, option, index); } @@ -79,9 +79,8 @@ QSize StarDelegate::sizeHint(const QStyleOptionViewItem &option, if (index.data().canConvert()) { StarRating starRating = qvariant_cast(index.data()); return starRating.sizeHint(); - } else { - return QStyledItemDelegate::sizeHint(option, index); } + return QStyledItemDelegate::sizeHint(option, index); } //! [1] @@ -96,9 +95,8 @@ QWidget *StarDelegate::createEditor(QWidget *parent, connect(editor, &StarEditor::editingFinished, this, &StarDelegate::commitAndCloseEditor); return editor; - } else { - return QStyledItemDelegate::createEditor(parent, option, index); } + return QStyledItemDelegate::createEditor(parent, option, index); } //! [2] diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.h b/examples/widgets/itemviews/stardelegate/stardelegate.h index ffc65fbedd..1fc31f8ee8 100644 --- a/examples/widgets/itemviews/stardelegate/stardelegate.h +++ b/examples/widgets/itemviews/stardelegate/stardelegate.h @@ -57,9 +57,8 @@ class StarDelegate : public QStyledItemDelegate { Q_OBJECT - public: - StarDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) {} + using QStyledItemDelegate::QStyledItemDelegate; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; diff --git a/examples/widgets/itemviews/stardelegate/stareditor.cpp b/examples/widgets/itemviews/stardelegate/stareditor.cpp index 19a4b54d9e..43706eeae0 100644 --- a/examples/widgets/itemviews/stardelegate/stareditor.cpp +++ b/examples/widgets/itemviews/stardelegate/stareditor.cpp @@ -48,11 +48,11 @@ ** ****************************************************************************/ -#include - #include "stareditor.h" #include "starrating.h" +#include + //! [0] StarEditor::StarEditor(QWidget *parent) : QWidget(parent) @@ -71,35 +71,37 @@ QSize StarEditor::sizeHint() const void StarEditor::paintEvent(QPaintEvent *) { QPainter painter(this); - myStarRating.paint(&painter, rect(), this->palette(), - StarRating::Editable); + myStarRating.paint(&painter, rect(), palette(), + StarRating::EditMode::Editable); } //! [1] //! [2] void StarEditor::mouseMoveEvent(QMouseEvent *event) { - int star = starAtPosition(event->x()); + const int star = starAtPosition(event->x()); if (star != myStarRating.starCount() && star != -1) { myStarRating.setStarCount(star); update(); } + QWidget::mouseMoveEvent(event); } //! [2] //! [3] -void StarEditor::mouseReleaseEvent(QMouseEvent * /* event */) +void StarEditor::mouseReleaseEvent(QMouseEvent *event) { emit editingFinished(); + QWidget::mouseReleaseEvent(event); } //! [3] //! [4] -int StarEditor::starAtPosition(int x) +int StarEditor::starAtPosition(int x) const { - int star = (x / (myStarRating.sizeHint().width() - / myStarRating.maxStarCount())) + 1; + const int star = (x / (myStarRating.sizeHint().width() + / myStarRating.maxStarCount())) + 1; if (star <= 0 || star > myStarRating.maxStarCount()) return -1; diff --git a/examples/widgets/itemviews/stardelegate/stareditor.h b/examples/widgets/itemviews/stardelegate/stareditor.h index 4a4c3a4954..8b1bf2efed 100644 --- a/examples/widgets/itemviews/stardelegate/stareditor.h +++ b/examples/widgets/itemviews/stardelegate/stareditor.h @@ -59,9 +59,8 @@ class StarEditor : public QWidget { Q_OBJECT - public: - StarEditor(QWidget *parent = 0); + StarEditor(QWidget *parent = nullptr); QSize sizeHint() const override; void setStarRating(const StarRating &starRating) { @@ -78,7 +77,7 @@ protected: void mouseReleaseEvent(QMouseEvent *event) override; private: - int starAtPosition(int x); + int starAtPosition(int x) const; StarRating myStarRating; }; diff --git a/examples/widgets/itemviews/stardelegate/starrating.cpp b/examples/widgets/itemviews/stardelegate/starrating.cpp index 845e474de9..15e14965e3 100644 --- a/examples/widgets/itemviews/stardelegate/starrating.cpp +++ b/examples/widgets/itemviews/stardelegate/starrating.cpp @@ -48,19 +48,18 @@ ** ****************************************************************************/ +#include "starrating.h" + #include #include -#include "starrating.h" - -const int PaintingScaleFactor = 20; +constexpr int PaintingScaleFactor = 20; //! [0] StarRating::StarRating(int starCount, int maxStarCount) + : myStarCount(starCount), + myMaxStarCount(maxStarCount) { - myStarCount = starCount; - myMaxStarCount = maxStarCount; - starPolygon << QPointF(1.0, 0.5); for (int i = 1; i < 5; ++i) starPolygon << QPointF(0.5 + 0.5 * std::cos(0.8 * i * 3.14), @@ -87,23 +86,19 @@ void StarRating::paint(QPainter *painter, const QRect &rect, painter->setRenderHint(QPainter::Antialiasing, true); painter->setPen(Qt::NoPen); + painter->setBrush(mode == EditMode::Editable ? + palette.highlight() : + palette.foreground()); - if (mode == Editable) { - painter->setBrush(palette.highlight()); - } else { - painter->setBrush(palette.foreground()); - } - - int yOffset = (rect.height() - PaintingScaleFactor) / 2; + const int yOffset = (rect.height() - PaintingScaleFactor) / 2; painter->translate(rect.x(), rect.y() + yOffset); painter->scale(PaintingScaleFactor, PaintingScaleFactor); for (int i = 0; i < myMaxStarCount; ++i) { - if (i < myStarCount) { + if (i < myStarCount) painter->drawPolygon(starPolygon, Qt::WindingFill); - } else if (mode == Editable) { + else if (mode == EditMode::Editable) painter->drawPolygon(diamondPolygon, Qt::WindingFill); - } painter->translate(1.0, 0.0); } diff --git a/examples/widgets/itemviews/stardelegate/starrating.h b/examples/widgets/itemviews/stardelegate/starrating.h index fa77311914..fc3028db58 100644 --- a/examples/widgets/itemviews/stardelegate/starrating.h +++ b/examples/widgets/itemviews/stardelegate/starrating.h @@ -51,15 +51,15 @@ #ifndef STARRATING_H #define STARRATING_H -#include -#include -#include +#include +#include +#include //! [0] class StarRating { public: - enum EditMode { Editable, ReadOnly }; + enum class EditMode { Editable, ReadOnly }; explicit StarRating(int starCount = 1, int maxStarCount = 5); -- cgit v1.2.3 From b5e0d854bd22e56e1567d0e6dd89e9eb7035338f Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 23 Nov 2018 19:33:22 +0100 Subject: Cleanup SimpleDomModel example Cleanup the SimpleDomModel example: - include own headers first - use nullptr - use const where possible - init members in initialization list Change-Id: If7029a774793927b9a3a9115ea4a7053402a86a1 Reviewed-by: Sze Howe Koh Reviewed-by: Luca Beldi --- .../widgets/itemviews/simpledommodel/domitem.cpp | 30 ++++++++-------- .../widgets/itemviews/simpledommodel/domitem.h | 6 ++-- .../widgets/itemviews/simpledommodel/dommodel.cpp | 40 ++++++++++++---------- .../widgets/itemviews/simpledommodel/dommodel.h | 2 +- .../itemviews/simpledommodel/mainwindow.cpp | 9 ++--- .../widgets/itemviews/simpledommodel/mainwindow.h | 2 +- 6 files changed, 45 insertions(+), 44 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/itemviews/simpledommodel/domitem.cpp b/examples/widgets/itemviews/simpledommodel/domitem.cpp index c8b35b2e0a..a2dc9530f0 100644 --- a/examples/widgets/itemviews/simpledommodel/domitem.cpp +++ b/examples/widgets/itemviews/simpledommodel/domitem.cpp @@ -53,23 +53,20 @@ #include //! [0] -DomItem::DomItem(QDomNode &node, int row, DomItem *parent) -{ - domNode = node; +DomItem::DomItem(const QDomNode &node, int row, DomItem *parent) + : domNode(node), //! [0] - // Record the item's location within its parent. + // Record the item's location within its parent. //! [1] - rowNumber = row; - parentItem = parent; -} + parentItem(parent), + rowNumber(row) +{} //! [1] //! [2] DomItem::~DomItem() { - QHash::iterator it; - for (it = childItems.begin(); it != childItems.end(); ++it) - delete it.value(); + qDeleteAll(childItems); } //! [2] @@ -90,21 +87,22 @@ DomItem *DomItem::parent() //! [5] DomItem *DomItem::child(int i) { - if (childItems.contains(i)) - return childItems[i]; + DomItem *childItem = childItems.value(i); + if (childItem) + return childItem; + // if child does not yet exist, create it if (i >= 0 && i < domNode.childNodes().count()) { QDomNode childNode = domNode.childNodes().item(i); - DomItem *childItem = new DomItem(childNode, i, this); + childItem = new DomItem(childNode, i, this); childItems[i] = childItem; - return childItem; } - return 0; + return childItem; } //! [5] //! [6] -int DomItem::row() +int DomItem::row() const { return rowNumber; } diff --git a/examples/widgets/itemviews/simpledommodel/domitem.h b/examples/widgets/itemviews/simpledommodel/domitem.h index b5db16009c..4a74db5139 100644 --- a/examples/widgets/itemviews/simpledommodel/domitem.h +++ b/examples/widgets/itemviews/simpledommodel/domitem.h @@ -58,16 +58,16 @@ class DomItem { public: - DomItem(QDomNode &node, int row, DomItem *parent = 0); + DomItem(const QDomNode &node, int row, DomItem *parent = nullptr); ~DomItem(); DomItem *child(int i); DomItem *parent(); QDomNode node() const; - int row(); + int row() const; private: QDomNode domNode; - QHash childItems; + QHash childItems; DomItem *parentItem; int rowNumber; }; diff --git a/examples/widgets/itemviews/simpledommodel/dommodel.cpp b/examples/widgets/itemviews/simpledommodel/dommodel.cpp index f9ba0b5801..8e15252ebb 100644 --- a/examples/widgets/itemviews/simpledommodel/dommodel.cpp +++ b/examples/widgets/itemviews/simpledommodel/dommodel.cpp @@ -48,16 +48,17 @@ ** ****************************************************************************/ -#include "domitem.h" #include "dommodel.h" +#include "domitem.h" #include //! [0] -DomModel::DomModel(QDomDocument document, QObject *parent) - : QAbstractItemModel(parent), domDocument(document) +DomModel::DomModel(const QDomDocument &document, QObject *parent) + : QAbstractItemModel(parent), + domDocument(document), + rootItem(new DomItem(domDocument, 0)) { - rootItem = new DomItem(domDocument, 0); } //! [0] @@ -69,8 +70,9 @@ DomModel::~DomModel() //! [1] //! [2] -int DomModel::columnCount(const QModelIndex &/*parent*/) const +int DomModel::columnCount(const QModelIndex &parent) const { + Q_UNUSED(parent); return 3; } //! [2] @@ -84,28 +86,31 @@ QVariant DomModel::data(const QModelIndex &index, int role) const if (role != Qt::DisplayRole) return QVariant(); - DomItem *item = static_cast(index.internalPointer()); + const DomItem *item = static_cast(index.internalPointer()); - QDomNode node = item->node(); + const QDomNode node = item->node(); //! [3] //! [4] - QStringList attributes; - QDomNamedNodeMap attributeMap = node.attributes(); switch (index.column()) { case 0: return node.nodeName(); case 1: + { + const QDomNamedNodeMap attributeMap = node.attributes(); + QStringList attributes; for (int i = 0; i < attributeMap.count(); ++i) { QDomNode attribute = attributeMap.item(i); attributes << attribute.nodeName() + "=\"" - +attribute.nodeValue() + '"'; + + attribute.nodeValue() + '"'; } return attributes.join(' '); + } case 2: - return node.nodeValue().split("\n").join(' '); + return node.nodeValue().split('\n').join(' '); default: - return QVariant(); + break; } + return QVariant(); } //! [4] @@ -113,7 +118,7 @@ QVariant DomModel::data(const QModelIndex &index, int role) const Qt::ItemFlags DomModel::flags(const QModelIndex &index) const { if (!index.isValid()) - return 0; + return Qt::NoItemFlags; return QAbstractItemModel::flags(index); } @@ -132,17 +137,15 @@ QVariant DomModel::headerData(int section, Qt::Orientation orientation, case 2: return tr("Value"); default: - return QVariant(); + break; } } - return QVariant(); } //! [6] //! [7] -QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) - const +QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); @@ -159,8 +162,7 @@ QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) DomItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); - else - return QModelIndex(); + return QModelIndex(); } //! [8] diff --git a/examples/widgets/itemviews/simpledommodel/dommodel.h b/examples/widgets/itemviews/simpledommodel/dommodel.h index 411f58295c..a91bb33cf9 100644 --- a/examples/widgets/itemviews/simpledommodel/dommodel.h +++ b/examples/widgets/itemviews/simpledommodel/dommodel.h @@ -63,7 +63,7 @@ class DomModel : public QAbstractItemModel Q_OBJECT public: - explicit DomModel(QDomDocument document, QObject *parent = 0); + explicit DomModel(const QDomDocument &document, QObject *parent = nullptr); ~DomModel(); QVariant data(const QModelIndex &index, int role) const override; diff --git a/examples/widgets/itemviews/simpledommodel/mainwindow.cpp b/examples/widgets/itemviews/simpledommodel/mainwindow.cpp index 7d43d0fc02..86543b07a6 100644 --- a/examples/widgets/itemviews/simpledommodel/mainwindow.cpp +++ b/examples/widgets/itemviews/simpledommodel/mainwindow.cpp @@ -48,22 +48,23 @@ ** ****************************************************************************/ -#include "dommodel.h" #include "mainwindow.h" +#include "dommodel.h" #include #include #include #include -MainWindow::MainWindow() : QMainWindow(), model(0) +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), + model(new DomModel(QDomDocument(), this)), + view(new QTreeView(this)) { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open); fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit); - model = new DomModel(QDomDocument(), this); - view = new QTreeView(this); view->setModel(model); setCentralWidget(view); diff --git a/examples/widgets/itemviews/simpledommodel/mainwindow.h b/examples/widgets/itemviews/simpledommodel/mainwindow.h index 938a1c54c1..b3f8d77f35 100644 --- a/examples/widgets/itemviews/simpledommodel/mainwindow.h +++ b/examples/widgets/itemviews/simpledommodel/mainwindow.h @@ -65,7 +65,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); public slots: void openFile(); -- cgit v1.2.3 From b688c7e99a8def9db836d1d6ab7388ae14a5d5b0 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Tue, 4 Dec 2018 17:44:20 +0100 Subject: DropSite example: fix documentation The DropSite documentation mentioned the foreach keyword which was removed some times ago in the code. Therefore also remove the corresponding documentation snippet. Change-Id: Id9dd3f01dbdd37eeda43fabe12b60ef9e0b32d10 Reviewed-by: Paul Wicking Reviewed-by: Friedemann Kleint --- examples/widgets/doc/dropsite.qdoc | 8 +------- examples/widgets/draganddrop/dropsite/dropsitewindow.cpp | 3 ++- 2 files changed, 3 insertions(+), 8 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/doc/dropsite.qdoc b/examples/widgets/doc/dropsite.qdoc index 32bcfe8916..af8766a308 100644 --- a/examples/widgets/doc/dropsite.qdoc +++ b/examples/widgets/doc/dropsite.qdoc @@ -202,13 +202,7 @@ \snippet draganddrop/dropsite/dropsitewindow.cpp updateFormatsTable() part1 Once we are sure that \c mimeData is valid, we iterate through its - supported formats using the \l{The foreach Keyword}{foreach keyword}. - This keyword has the following format: - - \include code/doc_src_examples_dropsite.qdoc 0 - - In our example, \c format is the \a variable and the \a container is a - QStringList, obtained from \c mimeData->formats(). + supported formats. \note The \l{QMimeData::formats()}{formats()} function returns a QStringList object, containing all the formats supported by the diff --git a/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp b/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp index 28a42ee614..2dae83bb22 100644 --- a/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp +++ b/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp @@ -113,7 +113,8 @@ void DropSiteWindow::updateFormatsTable(const QMimeData *mimeData) //! [updateFormatsTable() part1] //! [updateFormatsTable() part2] - for (const QString &format : mimeData->formats()) { + const QStringList formats = mimeData->formats(); + for (const QString &format : formats) { QTableWidgetItem *formatItem = new QTableWidgetItem(format); formatItem->setFlags(Qt::ItemIsEnabled); formatItem->setTextAlignment(Qt::AlignTop | Qt::AlignLeft); -- cgit v1.2.3 From 588bd92228efa7ed3a92929e0eb90c22be189e04 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 2 Dec 2018 14:17:21 +0100 Subject: Cleanup Widgets examples - parent ctor Cleanup the Widgets examples - add missing parent parameter Change-Id: I5cd7aa333dbb8e6e4b7b9e05c085120733da83ec Reviewed-by: Samuel Gaist Reviewed-by: Konstantin Shegunov Reviewed-by: Richard Moe Gustavsen Reviewed-by: Paul Wicking --- examples/widgets/widgets/calendarwidget/window.cpp | 3 ++- examples/widgets/widgets/calendarwidget/window.h | 2 +- examples/widgets/widgets/charactermap/mainwindow.cpp | 3 ++- examples/widgets/widgets/charactermap/mainwindow.h | 2 +- examples/widgets/widgets/icons/mainwindow.cpp | 3 ++- examples/widgets/widgets/icons/mainwindow.h | 2 +- examples/widgets/widgets/imageviewer/imageviewer.cpp | 7 +++---- examples/widgets/widgets/imageviewer/imageviewer.h | 2 +- examples/widgets/widgets/lineedits/window.cpp | 3 ++- examples/widgets/widgets/lineedits/window.h | 2 +- examples/widgets/widgets/mousebuttons/buttontester.h | 5 +++-- examples/widgets/widgets/scribble/mainwindow.cpp | 4 ++-- examples/widgets/widgets/scribble/mainwindow.h | 2 +- examples/widgets/widgets/sliders/window.cpp | 3 ++- examples/widgets/widgets/sliders/window.h | 2 +- examples/widgets/widgets/spinboxes/window.cpp | 3 ++- examples/widgets/widgets/spinboxes/window.h | 2 +- examples/widgets/widgets/stylesheet/mainwindow.cpp | 3 ++- examples/widgets/widgets/stylesheet/mainwindow.h | 2 +- examples/widgets/widgets/tetrix/tetrixwindow.cpp | 3 ++- examples/widgets/widgets/tetrix/tetrixwindow.h | 2 +- examples/widgets/widgets/tooltips/sortingbox.cpp | 3 ++- examples/widgets/widgets/tooltips/sortingbox.h | 2 +- examples/widgets/widgets/windowflags/controllerwindow.cpp | 3 ++- examples/widgets/widgets/windowflags/controllerwindow.h | 2 +- 25 files changed, 40 insertions(+), 30 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/calendarwidget/window.cpp b/examples/widgets/widgets/calendarwidget/window.cpp index c3a0e1e3f7..a1c1746786 100644 --- a/examples/widgets/widgets/calendarwidget/window.cpp +++ b/examples/widgets/widgets/calendarwidget/window.cpp @@ -53,7 +53,8 @@ #include "window.h" //! [0] -Window::Window() +Window::Window(QWidget *parent) + : QWidget(parent) { createPreviewGroupBox(); createGeneralOptionsGroupBox(); diff --git a/examples/widgets/widgets/calendarwidget/window.h b/examples/widgets/widgets/calendarwidget/window.h index fa01fc4db6..83ea494fc2 100644 --- a/examples/widgets/widgets/calendarwidget/window.h +++ b/examples/widgets/widgets/calendarwidget/window.h @@ -70,7 +70,7 @@ class Window : public QWidget Q_OBJECT public: - Window(); + Window(QWidget *parent = nullptr); private slots: void localeChanged(int index); diff --git a/examples/widgets/widgets/charactermap/mainwindow.cpp b/examples/widgets/widgets/charactermap/mainwindow.cpp index d3ac55483c..76bd8f7799 100644 --- a/examples/widgets/widgets/charactermap/mainwindow.cpp +++ b/examples/widgets/widgets/charactermap/mainwindow.cpp @@ -57,7 +57,8 @@ Q_DECLARE_METATYPE(QFontComboBox::FontFilter) -MainWindow::MainWindow() +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) { QMenu *fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(tr("Quit"), this, &QWidget::close); diff --git a/examples/widgets/widgets/charactermap/mainwindow.h b/examples/widgets/widgets/charactermap/mainwindow.h index eac16b35fa..79fe9f9cc8 100644 --- a/examples/widgets/widgets/charactermap/mainwindow.h +++ b/examples/widgets/widgets/charactermap/mainwindow.h @@ -70,7 +70,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); public slots: void filterChanged(int); diff --git a/examples/widgets/widgets/icons/mainwindow.cpp b/examples/widgets/widgets/icons/mainwindow.cpp index f704b8306f..904245494c 100644 --- a/examples/widgets/widgets/icons/mainwindow.cpp +++ b/examples/widgets/widgets/icons/mainwindow.cpp @@ -60,7 +60,8 @@ enum { OtherSize = QStyle::PM_CustomBase }; //! [40] //! [0] -MainWindow::MainWindow() +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) { QWidget *centralWidget = new QWidget(this); setCentralWidget(centralWidget); diff --git a/examples/widgets/widgets/icons/mainwindow.h b/examples/widgets/widgets/icons/mainwindow.h index e3888e5fb1..1949bd235c 100644 --- a/examples/widgets/widgets/icons/mainwindow.h +++ b/examples/widgets/widgets/icons/mainwindow.h @@ -74,7 +74,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); void loadImages(const QStringList &fileNames); diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp index 327abf7e43..b1346d9ccb 100644 --- a/examples/widgets/widgets/imageviewer/imageviewer.cpp +++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp @@ -59,10 +59,9 @@ #include "imageviewer.h" //! [0] -ImageViewer::ImageViewer() - : imageLabel(new QLabel) - , scrollArea(new QScrollArea) - , scaleFactor(1) +ImageViewer::ImageViewer(QWidget *parent) + : QMainWindow(parent), imageLabel(new QLabel), + scrollArea(new QScrollArea), scaleFactor(1) { imageLabel->setBackgroundRole(QPalette::Base); imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); diff --git a/examples/widgets/widgets/imageviewer/imageviewer.h b/examples/widgets/widgets/imageviewer/imageviewer.h index f4a62cafe9..7e53105b33 100644 --- a/examples/widgets/widgets/imageviewer/imageviewer.h +++ b/examples/widgets/widgets/imageviewer/imageviewer.h @@ -71,7 +71,7 @@ class ImageViewer : public QMainWindow Q_OBJECT public: - ImageViewer(); + ImageViewer(QWidget *parent = nullptr); bool loadFile(const QString &); private slots: diff --git a/examples/widgets/widgets/lineedits/window.cpp b/examples/widgets/widgets/lineedits/window.cpp index ffb1edc5ce..47324589b7 100644 --- a/examples/widgets/widgets/lineedits/window.cpp +++ b/examples/widgets/widgets/lineedits/window.cpp @@ -53,7 +53,8 @@ #include "window.h" //! [0] -Window::Window() +Window::Window(QWidget *parent) + : QWidget(parent) { QGroupBox *echoGroup = new QGroupBox(tr("Echo")); diff --git a/examples/widgets/widgets/lineedits/window.h b/examples/widgets/widgets/lineedits/window.h index 2070b3b84c..3231588f4f 100644 --- a/examples/widgets/widgets/lineedits/window.h +++ b/examples/widgets/widgets/lineedits/window.h @@ -64,7 +64,7 @@ class Window : public QWidget Q_OBJECT public: - Window(); + Window(QWidget *parent = nullptr); public slots: void echoChanged(int); diff --git a/examples/widgets/widgets/mousebuttons/buttontester.h b/examples/widgets/widgets/mousebuttons/buttontester.h index d99dcceb18..231733bd44 100644 --- a/examples/widgets/widgets/mousebuttons/buttontester.h +++ b/examples/widgets/widgets/mousebuttons/buttontester.h @@ -59,13 +59,14 @@ class ButtonTester : public QTextEdit { Q_OBJECT - +public: + using QTextEdit::QTextEdit; protected: void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void mouseDoubleClickEvent(QMouseEvent *event) override; #if QT_CONFIG(wheelevent) - void wheelEvent(QWheelEvent * event) override; + void wheelEvent(QWheelEvent *event) override; #endif int buttonByNumber(const Qt::MouseButton button); QString enumNameFromValue(const Qt::MouseButton button); diff --git a/examples/widgets/widgets/scribble/mainwindow.cpp b/examples/widgets/widgets/scribble/mainwindow.cpp index d54e5ce0f9..b8d01d505c 100644 --- a/examples/widgets/widgets/scribble/mainwindow.cpp +++ b/examples/widgets/widgets/scribble/mainwindow.cpp @@ -54,9 +54,9 @@ #include "scribblearea.h" //! [0] -MainWindow::MainWindow() +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), scribbleArea(new ScribbleArea(this)) { - scribbleArea = new ScribbleArea; setCentralWidget(scribbleArea); createActions(); diff --git a/examples/widgets/widgets/scribble/mainwindow.h b/examples/widgets/widgets/scribble/mainwindow.h index 9e0ddaff71..e57ff065ac 100644 --- a/examples/widgets/widgets/scribble/mainwindow.h +++ b/examples/widgets/widgets/scribble/mainwindow.h @@ -62,7 +62,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); protected: void closeEvent(QCloseEvent *event) override; diff --git a/examples/widgets/widgets/sliders/window.cpp b/examples/widgets/widgets/sliders/window.cpp index 16b60dde49..16467e71be 100644 --- a/examples/widgets/widgets/sliders/window.cpp +++ b/examples/widgets/widgets/sliders/window.cpp @@ -54,7 +54,8 @@ #include "window.h" //! [0] -Window::Window() +Window::Window(QWidget *parent) + : QWidget(parent) { horizontalSliders = new SlidersGroup(Qt::Horizontal, tr("Horizontal")); verticalSliders = new SlidersGroup(Qt::Vertical, tr("Vertical")); diff --git a/examples/widgets/widgets/sliders/window.h b/examples/widgets/widgets/sliders/window.h index 9c4c14fa37..4894781ac2 100644 --- a/examples/widgets/widgets/sliders/window.h +++ b/examples/widgets/widgets/sliders/window.h @@ -69,7 +69,7 @@ class Window : public QWidget Q_OBJECT public: - Window(); + Window(QWidget *parent = nullptr); private: void createControls(const QString &title); diff --git a/examples/widgets/widgets/spinboxes/window.cpp b/examples/widgets/widgets/spinboxes/window.cpp index 54604e35aa..eb660faace 100644 --- a/examples/widgets/widgets/spinboxes/window.cpp +++ b/examples/widgets/widgets/spinboxes/window.cpp @@ -53,7 +53,8 @@ #include "window.h" //! [0] -Window::Window() +Window::Window(QWidget *parent) + : QWidget(parent) { createSpinBoxes(); createDateTimeEdits(); diff --git a/examples/widgets/widgets/spinboxes/window.h b/examples/widgets/widgets/spinboxes/window.h index 97e9ac1083..138773a5aa 100644 --- a/examples/widgets/widgets/spinboxes/window.h +++ b/examples/widgets/widgets/spinboxes/window.h @@ -67,7 +67,7 @@ class Window : public QWidget Q_OBJECT public: - Window(); + Window(QWidget *parent = nullptr); public slots: void changePrecision(int decimals); diff --git a/examples/widgets/widgets/stylesheet/mainwindow.cpp b/examples/widgets/widgets/stylesheet/mainwindow.cpp index 9acd90658a..eb4b3a2424 100644 --- a/examples/widgets/widgets/stylesheet/mainwindow.cpp +++ b/examples/widgets/widgets/stylesheet/mainwindow.cpp @@ -53,7 +53,8 @@ #include "mainwindow.h" #include "stylesheeteditor.h" -MainWindow::MainWindow() +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) { ui.setupUi(this); diff --git a/examples/widgets/widgets/stylesheet/mainwindow.h b/examples/widgets/widgets/stylesheet/mainwindow.h index 46d3ecbb93..8af4c01da0 100644 --- a/examples/widgets/widgets/stylesheet/mainwindow.h +++ b/examples/widgets/widgets/stylesheet/mainwindow.h @@ -62,7 +62,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); private slots: void on_editStyleAction_triggered(); diff --git a/examples/widgets/widgets/tetrix/tetrixwindow.cpp b/examples/widgets/widgets/tetrix/tetrixwindow.cpp index 7e951aceb8..970a38c1dc 100644 --- a/examples/widgets/widgets/tetrix/tetrixwindow.cpp +++ b/examples/widgets/widgets/tetrix/tetrixwindow.cpp @@ -54,7 +54,8 @@ #include "tetrixwindow.h" //! [0] -TetrixWindow::TetrixWindow() +TetrixWindow::TetrixWindow(QWidget *parent) + : QWidget(parent) { board = new TetrixBoard; //! [0] diff --git a/examples/widgets/widgets/tetrix/tetrixwindow.h b/examples/widgets/widgets/tetrix/tetrixwindow.h index a21cef2ecf..02226ffe1c 100644 --- a/examples/widgets/widgets/tetrix/tetrixwindow.h +++ b/examples/widgets/widgets/tetrix/tetrixwindow.h @@ -67,7 +67,7 @@ class TetrixWindow : public QWidget Q_OBJECT public: - TetrixWindow(); + TetrixWindow(QWidget *parent = nullptr); private: QLabel *createLabel(const QString &text); diff --git a/examples/widgets/widgets/tooltips/sortingbox.cpp b/examples/widgets/widgets/tooltips/sortingbox.cpp index 4769a30c64..766815e8e9 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.cpp +++ b/examples/widgets/widgets/tooltips/sortingbox.cpp @@ -55,7 +55,8 @@ #include "sortingbox.h" //! [0] -SortingBox::SortingBox() +SortingBox::SortingBox(QWidget *parent) + : QWidget(parent) { //! [0] //! [1] setMouseTracking(true); diff --git a/examples/widgets/widgets/tooltips/sortingbox.h b/examples/widgets/widgets/tooltips/sortingbox.h index 2ac27614a5..12bdeff1f6 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.h +++ b/examples/widgets/widgets/tooltips/sortingbox.h @@ -67,7 +67,7 @@ class SortingBox : public QWidget Q_OBJECT public: - SortingBox(); + SortingBox(QWidget *parent = nullptr); protected: bool event(QEvent *event) override; diff --git a/examples/widgets/widgets/windowflags/controllerwindow.cpp b/examples/widgets/widgets/windowflags/controllerwindow.cpp index 78323810ed..c19f23c513 100644 --- a/examples/widgets/widgets/windowflags/controllerwindow.cpp +++ b/examples/widgets/widgets/windowflags/controllerwindow.cpp @@ -53,7 +53,8 @@ #include "controllerwindow.h" //! [0] -ControllerWindow::ControllerWindow() +ControllerWindow::ControllerWindow(QWidget *parent) + : QWidget(parent) { previewWindow = new PreviewWindow(this); diff --git a/examples/widgets/widgets/windowflags/controllerwindow.h b/examples/widgets/widgets/windowflags/controllerwindow.h index cfb88ed20f..43ec67e27f 100644 --- a/examples/widgets/widgets/windowflags/controllerwindow.h +++ b/examples/widgets/widgets/windowflags/controllerwindow.h @@ -69,7 +69,7 @@ class ControllerWindow : public QWidget Q_OBJECT public: - ControllerWindow(); + ControllerWindow(QWidget *parent = nullptr); private slots: void updatePreview(); -- cgit v1.2.3 From b8720e3e7a93121cd2e6dc081d872e8000ce81c9 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 2 Dec 2018 14:39:55 +0100 Subject: Cleanup Widgets examples - Validator example Cleanup the widgets examples - move the ValidatorWidget class into its own source/header file instead of implementing it in main.cpp Change-Id: I2b74ca4f2491168453dc31e0631f31e3ac83123c Reviewed-by: Konstantin Shegunov Reviewed-by: Samuel Gaist Reviewed-by: Richard Moe Gustavsen --- examples/widgets/widgets/validators/main.cpp | 85 +------------- examples/widgets/widgets/validators/validators.pro | 4 +- .../widgets/widgets/validators/validatorwidget.cpp | 122 +++++++++++++++++++++ .../widgets/widgets/validators/validatorwidget.h | 64 +++++++++++ 4 files changed, 190 insertions(+), 85 deletions(-) create mode 100644 examples/widgets/widgets/validators/validatorwidget.cpp create mode 100644 examples/widgets/widgets/validators/validatorwidget.h (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/validators/main.cpp b/examples/widgets/widgets/validators/main.cpp index d8ba2943d0..1fbf12410d 100644 --- a/examples/widgets/widgets/validators/main.cpp +++ b/examples/widgets/widgets/validators/main.cpp @@ -48,88 +48,9 @@ ** ****************************************************************************/ -#include -#include -#include -#include - -#include "ui_validators.h" - -class ValidatorWidget : public QWidget, public Ui::ValidatorsForm -{ - Q_OBJECT -public: - ValidatorWidget(QWidget *parent = 0); - -private slots: - void updateValidator(); - void updateDoubleValidator(); - void _setLocale(const QLocale &l) { setLocale(l); updateValidator(); updateDoubleValidator(); } - -private: - QIntValidator *validator; - QDoubleValidator *doubleValidator; -}; - -ValidatorWidget::ValidatorWidget(QWidget *parent) - : QWidget(parent) -{ - setupUi(this); - - connect(localeSelector, SIGNAL(localeSelected(QLocale)), this, SLOT(_setLocale(QLocale))); - - connect(minVal, SIGNAL(editingFinished()), this, SLOT(updateValidator())); - connect(maxVal, SIGNAL(editingFinished()), this, SLOT(updateValidator())); - connect(editor, SIGNAL(editingFinished()), ledWidget, SLOT(flash())); - - connect(doubleMaxVal, SIGNAL(editingFinished()), this, SLOT(updateDoubleValidator())); - connect(doubleMinVal, SIGNAL(editingFinished()), this, SLOT(updateDoubleValidator())); - connect(doubleDecimals, SIGNAL(valueChanged(int)), this, SLOT(updateDoubleValidator())); - connect(doubleFormat, SIGNAL(activated(int)), this, SLOT(updateDoubleValidator())); - connect(doubleEditor, SIGNAL(editingFinished()), doubleLedWidget, SLOT(flash())); +#include "validatorwidget.h" - validator = 0; - doubleValidator = 0; - updateValidator(); - updateDoubleValidator(); -}; - -void ValidatorWidget::updateValidator() -{ - QIntValidator *v = new QIntValidator(minVal->value(), maxVal->value(), this); - v->setLocale(locale()); - editor->setValidator(v); - delete validator; - validator = v; - - QString s = editor->text(); - int i = 0; - if (validator->validate(s, i) == QValidator::Invalid) { - editor->clear(); - } else { - editor->setText(s); - } -} - -void ValidatorWidget::updateDoubleValidator() -{ - QDoubleValidator *v - = new QDoubleValidator(doubleMinVal->value(), doubleMaxVal->value(), - doubleDecimals->value(), this); - v->setNotation(static_cast(doubleFormat->currentIndex())); - v->setLocale(locale()); - doubleEditor->setValidator(v); - delete doubleValidator; - doubleValidator = v; - - QString s = doubleEditor->text(); - int i = 0; - if (doubleValidator->validate(s, i) == QValidator::Invalid) { - doubleEditor->clear(); - } else { - doubleEditor->setText(s); - } -} +#include int main(int argc, char **argv) { @@ -142,5 +63,3 @@ int main(int argc, char **argv) return app.exec(); } - -#include "main.moc" diff --git a/examples/widgets/widgets/validators/validators.pro b/examples/widgets/widgets/validators/validators.pro index ab1eb7809b..029cf95aca 100644 --- a/examples/widgets/widgets/validators/validators.pro +++ b/examples/widgets/widgets/validators/validators.pro @@ -4,8 +4,8 @@ requires(qtConfig(combobox)) FORMS += validators.ui RESOURCES += validators.qrc -SOURCES += main.cpp ledwidget.cpp localeselector.cpp -HEADERS += ledwidget.h localeselector.h +SOURCES += main.cpp ledwidget.cpp localeselector.cpp validatorwidget.cpp +HEADERS += ledwidget.h localeselector.h validatorwidget.h # install target.path = $$[QT_INSTALL_EXAMPLES]/widgets/widgets/validators diff --git a/examples/widgets/widgets/validators/validatorwidget.cpp b/examples/widgets/widgets/validators/validatorwidget.cpp new file mode 100644 index 0000000000..fa0a55aa52 --- /dev/null +++ b/examples/widgets/widgets/validators/validatorwidget.cpp @@ -0,0 +1,122 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "validatorwidget.h" + +#include + +ValidatorWidget::ValidatorWidget(QWidget *parent) + : QWidget(parent) +{ + setupUi(this); + + connect(localeSelector, &LocaleSelector::localeSelected, + this, &ValidatorWidget::setLocale); + connect(localeSelector, &LocaleSelector::localeSelected, + this, &ValidatorWidget::updateValidator); + connect(localeSelector, &LocaleSelector::localeSelected, + this, &ValidatorWidget::updateDoubleValidator); + + connect(minVal, &QSpinBox::editingFinished, + this, &ValidatorWidget::updateValidator); + connect(maxVal, &QSpinBox::editingFinished, + this, &ValidatorWidget::updateValidator); + connect(editor, &QLineEdit::editingFinished, + ledWidget, &LEDWidget::flash); + + connect(doubleMaxVal, &QDoubleSpinBox::editingFinished, + this, &ValidatorWidget::updateDoubleValidator); + connect(doubleMinVal, &QDoubleSpinBox::editingFinished, + this, &ValidatorWidget::updateDoubleValidator); + connect(doubleDecimals, QOverload::of(&QSpinBox::valueChanged), + this, &ValidatorWidget::updateDoubleValidator); + connect(doubleFormat, QOverload::of(&QComboBox::activated), + this, &ValidatorWidget::updateDoubleValidator); + connect(doubleEditor, &QLineEdit::editingFinished, + doubleLedWidget, &LEDWidget::flash); + + updateValidator(); + updateDoubleValidator(); +} + +void ValidatorWidget::updateValidator() +{ + QIntValidator *v = new QIntValidator(minVal->value(), maxVal->value(), this); + v->setLocale(locale()); + delete editor->validator(); + editor->setValidator(v); + + QString s = editor->text(); + int i = 0; + if (v->validate(s, i) == QValidator::Invalid) { + editor->clear(); + } else { + editor->setText(s); + } +} + +void ValidatorWidget::updateDoubleValidator() +{ + QDoubleValidator *v + = new QDoubleValidator(doubleMinVal->value(), doubleMaxVal->value(), + doubleDecimals->value(), this); + v->setNotation(static_cast(doubleFormat->currentIndex())); + v->setLocale(locale()); + delete doubleEditor->validator(); + doubleEditor->setValidator(v); + + QString s = doubleEditor->text(); + int i = 0; + if (v->validate(s, i) == QValidator::Invalid) { + doubleEditor->clear(); + } else { + doubleEditor->setText(s); + } +} diff --git a/examples/widgets/widgets/validators/validatorwidget.h b/examples/widgets/widgets/validators/validatorwidget.h new file mode 100644 index 0000000000..bcc4a9b91e --- /dev/null +++ b/examples/widgets/widgets/validators/validatorwidget.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "ui_validators.h" + +class ValidatorWidget : public QWidget, public Ui::ValidatorsForm +{ + Q_OBJECT +public: + ValidatorWidget(QWidget *parent = nullptr); + +private slots: + void updateValidator(); + void updateDoubleValidator(); +}; -- cgit v1.2.3 From af84f12298e7ba51d4121f9dd7a1b6e3ba050266 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sat, 24 Nov 2018 17:29:15 +0100 Subject: Cleanup Itemviews examples Cleanup the Itemviews examples - use nullptr instead 0 - use for loop instead foreach - include own header first - remove uselss includes Change-Id: I32e9f64356e42038707d063dcad977239ce1fe9e Reviewed-by: Luca Beldi Reviewed-by: Sze Howe Koh --- .../coloreditorfactory/colorlisteditor.cpp | 10 ++++----- .../itemviews/coloreditorfactory/colorlisteditor.h | 4 ++-- .../itemviews/coloreditorfactory/window.cpp | 17 +++++++-------- .../customsortfiltermodel/filterwidget.cpp | 5 ++--- .../itemviews/customsortfiltermodel/filterwidget.h | 2 +- .../mysortfilterproxymodel.cpp | 6 +++--- .../itemviews/customsortfiltermodel/window.cpp | 13 +++++++---- .../widgets/itemviews/fetchmore/filelistmodel.cpp | 25 +++++++++++----------- .../widgets/itemviews/fetchmore/filelistmodel.h | 3 +-- examples/widgets/itemviews/fetchmore/window.cpp | 4 ++-- examples/widgets/itemviews/fetchmore/window.h | 2 +- examples/widgets/itemviews/interview/model.cpp | 3 +-- examples/widgets/itemviews/interview/model.h | 4 ++-- .../widgets/itemviews/pixelator/mainwindow.cpp | 2 +- .../widgets/itemviews/pixelator/pixeldelegate.cpp | 14 ++++++------ .../widgets/itemviews/pixelator/pixeldelegate.h | 6 +++--- examples/widgets/itemviews/puzzle/piecesmodel.cpp | 9 +++----- examples/widgets/itemviews/puzzle/piecesmodel.h | 10 ++++----- .../widgets/itemviews/simplewidgetmapper/window.h | 2 +- .../widgets/itemviews/spinboxdelegate/delegate.cpp | 7 +++--- .../widgets/itemviews/spinboxdelegate/delegate.h | 6 +++--- examples/widgets/itemviews/storageview/main.cpp | 7 +++--- .../widgets/itemviews/storageview/storagemodel.cpp | 8 ------- .../widgets/itemviews/storageview/storagemodel.h | 2 +- 24 files changed, 79 insertions(+), 92 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp index 75d809a44f..0b65c53477 100644 --- a/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp +++ b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "colorlisteditor.h" +#include + ColorListEditor::ColorListEditor(QWidget *widget) : QComboBox(widget) { populateList(); @@ -65,16 +65,16 @@ QColor ColorListEditor::color() const //! [0] //! [1] -void ColorListEditor::setColor(QColor color) +void ColorListEditor::setColor(const QColor &color) { - setCurrentIndex(findData(color, int(Qt::DecorationRole))); + setCurrentIndex(findData(color, Qt::DecorationRole)); } //! [1] //! [2] void ColorListEditor::populateList() { - QStringList colorNames = QColor::colorNames(); + const QStringList colorNames = QColor::colorNames(); for (int i = 0; i < colorNames.size(); ++i) { QColor color(colorNames[i]); diff --git a/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h index f284c07c89..f9d736d298 100644 --- a/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h +++ b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h @@ -65,11 +65,11 @@ class ColorListEditor : public QComboBox Q_PROPERTY(QColor color READ color WRITE setColor USER true) public: - ColorListEditor(QWidget *widget = 0); + ColorListEditor(QWidget *widget = nullptr); public: QColor color() const; - void setColor(QColor c); + void setColor(const QColor &color); private: void populateList(); diff --git a/examples/widgets/itemviews/coloreditorfactory/window.cpp b/examples/widgets/itemviews/coloreditorfactory/window.cpp index f7ce821d31..e4a9379d8f 100644 --- a/examples/widgets/itemviews/coloreditorfactory/window.cpp +++ b/examples/widgets/itemviews/coloreditorfactory/window.cpp @@ -48,11 +48,11 @@ ** ****************************************************************************/ -#include - #include "window.h" #include "colorlisteditor.h" +#include + //! [0] Window::Window() { @@ -71,19 +71,18 @@ Window::Window() void Window::createGUI() { - QList > list; - list << QPair(tr("Alice"), QColor("aliceblue")) << - QPair(tr("Neptun"), QColor("aquamarine")) << - QPair(tr("Ferdinand"), QColor("springgreen")); + const QVector > list = + {{ tr("Alice"), QColor("aliceblue") }, + { tr("Neptun"), QColor("aquamarine") }, + { tr("Ferdinand"), QColor("springgreen") }}; QTableWidget *table = new QTableWidget(3, 2); - table->setHorizontalHeaderLabels(QStringList() << tr("Name") - << tr("Hair Color")); + table->setHorizontalHeaderLabels({ tr("Name"), tr("Hair Color") }); table->verticalHeader()->setVisible(false); table->resize(150, 50); for (int i = 0; i < 3; ++i) { - QPair pair = list.at(i); + const QPair &pair = list.at(i); QTableWidgetItem *nameItem = new QTableWidgetItem(pair.first); QTableWidgetItem *colorItem = new QTableWidgetItem; diff --git a/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp b/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp index 74d88caae6..302042a6b3 100644 --- a/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp +++ b/examples/widgets/itemviews/customsortfiltermodel/filterwidget.cpp @@ -52,13 +52,11 @@ #include #include -#include #include #include #include #include #include -#include FilterWidget::FilterWidget(QWidget *parent) : QLineEdit(parent) @@ -127,7 +125,8 @@ QRegExp::PatternSyntax FilterWidget::patternSyntax() const void FilterWidget::setPatternSyntax(QRegExp::PatternSyntax s) { - foreach (QAction *a, m_patternGroup->actions()) { + const QList actions = m_patternGroup->actions(); + for (QAction *a : actions) { if (patternSyntaxFromAction(a) == s) { a->setChecked(true); break; diff --git a/examples/widgets/itemviews/customsortfiltermodel/filterwidget.h b/examples/widgets/itemviews/customsortfiltermodel/filterwidget.h index ea12954e52..70214b862e 100644 --- a/examples/widgets/itemviews/customsortfiltermodel/filterwidget.h +++ b/examples/widgets/itemviews/customsortfiltermodel/filterwidget.h @@ -67,7 +67,7 @@ class FilterWidget : public QLineEdit Q_PROPERTY(Qt::CaseSensitivity caseSensitivity READ caseSensitivity WRITE setCaseSensitivity) Q_PROPERTY(QRegExp::PatternSyntax patternSyntax READ patternSyntax WRITE setPatternSyntax) public: - explicit FilterWidget(QWidget *parent = 0); + explicit FilterWidget(QWidget *parent = nullptr); Qt::CaseSensitivity caseSensitivity() const; void setCaseSensitivity(Qt::CaseSensitivity); diff --git a/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp b/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp index 35426657d9..4753d04d9b 100644 --- a/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp +++ b/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "mysortfilterproxymodel.h" +#include + //! [0] MySortFilterProxyModel::MySortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent) @@ -77,7 +77,7 @@ void MySortFilterProxyModel::setFilterMaximumDate(const QDate &date) //! [3] bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow, - const QModelIndex &sourceParent) const + const QModelIndex &sourceParent) const { QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent); diff --git a/examples/widgets/itemviews/customsortfiltermodel/window.cpp b/examples/widgets/itemviews/customsortfiltermodel/window.cpp index bfd2350da0..3356c971ad 100644 --- a/examples/widgets/itemviews/customsortfiltermodel/window.cpp +++ b/examples/widgets/itemviews/customsortfiltermodel/window.cpp @@ -48,12 +48,12 @@ ** ****************************************************************************/ -#include - -#include "mysortfilterproxymodel.h" #include "window.h" +#include "mysortfilterproxymodel.h" #include "filterwidget.h" +#include + //! [0] Window::Window() { @@ -75,7 +75,7 @@ Window::Window() //! [3] filterWidget = new FilterWidget; - filterWidget->setText("Grace|Sports"); + filterWidget->setText(tr("Grace|Sports")); connect(filterWidget, &FilterWidget::filterChanged, this, &Window::textFilterChanged); filterPatternLabel = new QLabel(tr("&Filter pattern:")); @@ -137,6 +137,11 @@ void Window::setSourceModel(QAbstractItemModel *model) { proxyModel->setSourceModel(model); sourceView->setModel(model); + + for (int i = 0; i < proxyModel->columnCount(); ++i) + proxyView->resizeColumnToContents(i); + for (int i = 0; i < model->columnCount(); ++i) + sourceView->resizeColumnToContents(i); } //! [7] diff --git a/examples/widgets/itemviews/fetchmore/filelistmodel.cpp b/examples/widgets/itemviews/fetchmore/filelistmodel.cpp index 086d45eca3..3ee80617c0 100644 --- a/examples/widgets/itemviews/fetchmore/filelistmodel.cpp +++ b/examples/widgets/itemviews/fetchmore/filelistmodel.cpp @@ -50,20 +50,18 @@ #include "filelistmodel.h" -#include -#include +#include #include #include FileListModel::FileListModel(QObject *parent) - : QAbstractListModel(parent) -{ -} + : QAbstractListModel(parent), fileCount(0) +{} //![4] -int FileListModel::rowCount(const QModelIndex & /* parent */) const +int FileListModel::rowCount(const QModelIndex &parent) const { - return fileCount; + return parent.isValid() ? 0 : fileCount; } QVariant FileListModel::data(const QModelIndex &index, int role) const @@ -88,25 +86,26 @@ QVariant FileListModel::data(const QModelIndex &index, int role) const //![4] //![1] -bool FileListModel::canFetchMore(const QModelIndex & /* index */) const +bool FileListModel::canFetchMore(const QModelIndex &parent) const { - if (fileCount < fileList.size()) - return true; - else + if (parent.isValid()) return false; + return (fileCount < fileList.size()); } //![1] //![2] -void FileListModel::fetchMore(const QModelIndex & /* index */) +void FileListModel::fetchMore(const QModelIndex &parent) { + if (parent.isValid()) + return; int remainder = fileList.size() - fileCount; int itemsToFetch = qMin(100, remainder); if (itemsToFetch <= 0) return; - beginInsertRows(QModelIndex(), fileCount, fileCount+itemsToFetch-1); + beginInsertRows(QModelIndex(), fileCount, fileCount + itemsToFetch - 1); fileCount += itemsToFetch; diff --git a/examples/widgets/itemviews/fetchmore/filelistmodel.h b/examples/widgets/itemviews/fetchmore/filelistmodel.h index 9251eaf959..35cf6f7b46 100644 --- a/examples/widgets/itemviews/fetchmore/filelistmodel.h +++ b/examples/widgets/itemviews/fetchmore/filelistmodel.h @@ -52,7 +52,6 @@ #define FILELISTMODEL_H #include -#include #include //![0] @@ -61,7 +60,7 @@ class FileListModel : public QAbstractListModel Q_OBJECT public: - FileListModel(QObject *parent = 0); + FileListModel(QObject *parent = nullptr); int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; diff --git a/examples/widgets/itemviews/fetchmore/window.cpp b/examples/widgets/itemviews/fetchmore/window.cpp index 886f76d6ab..d71ac7059d 100644 --- a/examples/widgets/itemviews/fetchmore/window.cpp +++ b/examples/widgets/itemviews/fetchmore/window.cpp @@ -48,8 +48,8 @@ ** ****************************************************************************/ -#include "filelistmodel.h" #include "window.h" +#include "filelistmodel.h" #include @@ -66,7 +66,7 @@ Window::Window(QWidget *parent) QListView *view = new QListView; view->setModel(model); - logViewer = new QTextBrowser; + logViewer = new QTextBrowser(this); logViewer->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); connect(lineEdit, &QLineEdit::textChanged, diff --git a/examples/widgets/itemviews/fetchmore/window.h b/examples/widgets/itemviews/fetchmore/window.h index f234683785..61bcb94bde 100644 --- a/examples/widgets/itemviews/fetchmore/window.h +++ b/examples/widgets/itemviews/fetchmore/window.h @@ -62,7 +62,7 @@ class Window : public QWidget Q_OBJECT public: - Window(QWidget *parent = 0); + Window(QWidget *parent = nullptr); public slots: void updateLog(int number); diff --git a/examples/widgets/itemviews/interview/model.cpp b/examples/widgets/itemviews/interview/model.cpp index a8f3a6f31e..feaf8bb98c 100644 --- a/examples/widgets/itemviews/interview/model.cpp +++ b/examples/widgets/itemviews/interview/model.cpp @@ -50,14 +50,13 @@ #include "model.h" -#include #include Model::Model(int rows, int columns, QObject *parent) : QAbstractItemModel(parent), services(QPixmap(":/images/services.png")), rc(rows), cc(columns), - tree(new QVector(rows, Node(0))) + tree(new QVector(rows, Node())) { } diff --git a/examples/widgets/itemviews/interview/model.h b/examples/widgets/itemviews/interview/model.h index 969cf693b2..132f1d01aa 100644 --- a/examples/widgets/itemviews/interview/model.h +++ b/examples/widgets/itemviews/interview/model.h @@ -61,7 +61,7 @@ class Model : public QAbstractItemModel Q_OBJECT public: - Model(int rows, int columns, QObject *parent = 0); + Model(int rows, int columns, QObject *parent = nullptr); ~Model(); QModelIndex index(int row, int column, const QModelIndex &parent) const override; @@ -80,7 +80,7 @@ private: struct Node { - Node(Node *parent = 0) : parent(parent), children(0) {} + Node(Node *parent = nullptr) : parent(parent), children(nullptr) {} ~Node() { delete children; } Node *parent; QVector *children; diff --git a/examples/widgets/itemviews/pixelator/mainwindow.cpp b/examples/widgets/itemviews/pixelator/mainwindow.cpp index 63617f0169..f6b67e4dba 100644 --- a/examples/widgets/itemviews/pixelator/mainwindow.cpp +++ b/examples/widgets/itemviews/pixelator/mainwindow.cpp @@ -48,8 +48,8 @@ ** ****************************************************************************/ -#include "imagemodel.h" #include "mainwindow.h" +#include "imagemodel.h" #include "pixeldelegate.h" #include diff --git a/examples/widgets/itemviews/pixelator/pixeldelegate.cpp b/examples/widgets/itemviews/pixelator/pixeldelegate.cpp index ecf44c1224..dc8736c836 100644 --- a/examples/widgets/itemviews/pixelator/pixeldelegate.cpp +++ b/examples/widgets/itemviews/pixelator/pixeldelegate.cpp @@ -54,10 +54,8 @@ //! [0] PixelDelegate::PixelDelegate(QObject *parent) - : QAbstractItemDelegate(parent) -{ - pixelSize = 12; -} + : QAbstractItemDelegate(parent), pixelSize(12) +{} //! [0] //! [1] @@ -70,11 +68,11 @@ void PixelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, //! [1] //! [3] - int size = qMin(option.rect.width(), option.rect.height()); + const int size = qMin(option.rect.width(), option.rect.height()); //! [3] //! [4] - int brightness = index.model()->data(index, Qt::DisplayRole).toInt(); - double radius = (size / 2.0) - (brightness / 255.0 * size / 2.0); - if (radius == 0.0) + const int brightness = index.model()->data(index, Qt::DisplayRole).toInt(); + const double radius = (size / 2.0) - (brightness / 255.0 * size / 2.0); + if (qFuzzyIsNull(radius)) return; //! [4] diff --git a/examples/widgets/itemviews/pixelator/pixeldelegate.h b/examples/widgets/itemviews/pixelator/pixeldelegate.h index d968d9e8d2..9f52221a28 100644 --- a/examples/widgets/itemviews/pixelator/pixeldelegate.h +++ b/examples/widgets/itemviews/pixelator/pixeldelegate.h @@ -61,7 +61,7 @@ class QObject; class QPainter; QT_END_NAMESPACE -static const int ItemSize = 256; +static constexpr int ItemSize = 256; //! [0] class PixelDelegate : public QAbstractItemDelegate @@ -69,13 +69,13 @@ class PixelDelegate : public QAbstractItemDelegate Q_OBJECT public: - PixelDelegate(QObject *parent = 0); + PixelDelegate(QObject *parent = nullptr); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index ) const override; + const QModelIndex &index) const override; public slots: void setPixelSize(int size); diff --git a/examples/widgets/itemviews/puzzle/piecesmodel.cpp b/examples/widgets/itemviews/puzzle/piecesmodel.cpp index 28b46836f4..a9c53ed2cd 100644 --- a/examples/widgets/itemviews/puzzle/piecesmodel.cpp +++ b/examples/widgets/itemviews/puzzle/piecesmodel.cpp @@ -134,7 +134,7 @@ QMimeData *PiecesModel::mimeData(const QModelIndexList &indexes) const QDataStream stream(&encodedData, QIODevice::WriteOnly); - foreach (QModelIndex index, indexes) { + for (const QModelIndex &index : indexes) { if (index.isValid()) { QPixmap pixmap = qvariant_cast(data(index, Qt::UserRole)); QPoint location = data(index, Qt::UserRole+1).toPoint(); @@ -190,10 +190,7 @@ bool PiecesModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int PiecesModel::rowCount(const QModelIndex &parent) const { - if (parent.isValid()) - return 0; - else - return pixmaps.size(); + return parent.isValid() ? 0 : pixmaps.size(); } Qt::DropActions PiecesModel::supportedDropActions() const @@ -201,7 +198,7 @@ Qt::DropActions PiecesModel::supportedDropActions() const return Qt::CopyAction | Qt::MoveAction; } -void PiecesModel::addPieces(const QPixmap& pixmap) +void PiecesModel::addPieces(const QPixmap &pixmap) { if (!pixmaps.isEmpty()) { beginRemoveRows(QModelIndex(), 0, pixmaps.size() - 1); diff --git a/examples/widgets/itemviews/puzzle/piecesmodel.h b/examples/widgets/itemviews/puzzle/piecesmodel.h index bd979f4c7e..2a96603707 100644 --- a/examples/widgets/itemviews/puzzle/piecesmodel.h +++ b/examples/widgets/itemviews/puzzle/piecesmodel.h @@ -52,10 +52,10 @@ #define PIECESLIST_H #include -#include #include #include #include +#include QT_BEGIN_NAMESPACE class QMimeData; @@ -66,7 +66,7 @@ class PiecesModel : public QAbstractListModel Q_OBJECT public: - explicit PiecesModel(int pieceSize, QObject *parent = 0); + explicit PiecesModel(int pieceSize, QObject *parent = nullptr); QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; @@ -80,11 +80,11 @@ public: Qt::DropActions supportedDropActions() const override; void addPiece(const QPixmap &pixmap, const QPoint &location); - void addPieces(const QPixmap& pixmap); + void addPieces(const QPixmap &pixmap); private: - QList locations; - QList pixmaps; + QVector locations; + QVector pixmaps; int m_PieceSize; }; diff --git a/examples/widgets/itemviews/simplewidgetmapper/window.h b/examples/widgets/itemviews/simplewidgetmapper/window.h index baa087f8ae..d04b528e16 100644 --- a/examples/widgets/itemviews/simplewidgetmapper/window.h +++ b/examples/widgets/itemviews/simplewidgetmapper/window.h @@ -69,7 +69,7 @@ class Window : public QWidget Q_OBJECT public: - Window(QWidget *parent = 0); + Window(QWidget *parent = nullptr); private slots: void updateButtons(int row); diff --git a/examples/widgets/itemviews/spinboxdelegate/delegate.cpp b/examples/widgets/itemviews/spinboxdelegate/delegate.cpp index e7e03688c3..f0fe524a60 100644 --- a/examples/widgets/itemviews/spinboxdelegate/delegate.cpp +++ b/examples/widgets/itemviews/spinboxdelegate/delegate.cpp @@ -68,8 +68,8 @@ SpinBoxDelegate::SpinBoxDelegate(QObject *parent) //! [1] QWidget *SpinBoxDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &/* option */, - const QModelIndex &/* index */) const + const QStyleOptionViewItem &/* option */, + const QModelIndex &/* index */) const { QSpinBox *editor = new QSpinBox(parent); editor->setFrame(false); @@ -105,7 +105,8 @@ void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, //! [4] void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &/* index */) const + const QStyleOptionViewItem &option, + const QModelIndex &/* index */) const { editor->setGeometry(option.rect); } diff --git a/examples/widgets/itemviews/spinboxdelegate/delegate.h b/examples/widgets/itemviews/spinboxdelegate/delegate.h index 47ef1555f7..5dbdda9cd0 100644 --- a/examples/widgets/itemviews/spinboxdelegate/delegate.h +++ b/examples/widgets/itemviews/spinboxdelegate/delegate.h @@ -59,7 +59,7 @@ class SpinBoxDelegate : public QStyledItemDelegate Q_OBJECT public: - SpinBoxDelegate(QObject *parent = 0); + SpinBoxDelegate(QObject *parent = nullptr); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; @@ -68,8 +68,8 @@ public: void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; }; //! [0] diff --git a/examples/widgets/itemviews/storageview/main.cpp b/examples/widgets/itemviews/storageview/main.cpp index f349e58fad..8f23a4820a 100644 --- a/examples/widgets/itemviews/storageview/main.cpp +++ b/examples/widgets/itemviews/storageview/main.cpp @@ -49,10 +49,9 @@ ** ****************************************************************************/ -#include -#include -#include -#include +#include +#include +#include #include "storagemodel.h" diff --git a/examples/widgets/itemviews/storageview/storagemodel.cpp b/examples/widgets/itemviews/storageview/storagemodel.cpp index 063f126d86..b98fc8445c 100644 --- a/examples/widgets/itemviews/storageview/storagemodel.cpp +++ b/examples/widgets/itemviews/storageview/storagemodel.cpp @@ -53,14 +53,6 @@ #include #include -#include -#include -#include - -StorageModel::StorageModel(QObject *parent) : - QAbstractTableModel(parent) -{ -} void StorageModel::refresh() { diff --git a/examples/widgets/itemviews/storageview/storagemodel.h b/examples/widgets/itemviews/storageview/storagemodel.h index 787b2f04de..597218c220 100644 --- a/examples/widgets/itemviews/storageview/storagemodel.h +++ b/examples/widgets/itemviews/storageview/storagemodel.h @@ -74,7 +74,7 @@ public: ColumnCount }; - explicit StorageModel(QObject *parent = nullptr); + using QAbstractTableModel::QAbstractTableModel; int columnCount(const QModelIndex &parent) const override; int rowCount(const QModelIndex &parent) const override; -- cgit v1.2.3 From c8720d62102f4e53f12117835735259d20e99433 Mon Sep 17 00:00:00 2001 From: Jeremy Whiting Date: Tue, 18 Dec 2018 21:15:15 -0700 Subject: Fix typo in fetchmore example documentation In fetchmore example documentation there's a typo on the first line. The text should read 'shows how to' but instead reads 'shows how two' Change-Id: Ifc169581e8fc43315dc01c7d1f267dd45600af82 Reviewed-by: Frederik Gladhorn --- examples/widgets/doc/src/fetchmore.qdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples/widgets') diff --git a/examples/widgets/doc/src/fetchmore.qdoc b/examples/widgets/doc/src/fetchmore.qdoc index df0cf3b8ec..a27efaf071 100644 --- a/examples/widgets/doc/src/fetchmore.qdoc +++ b/examples/widgets/doc/src/fetchmore.qdoc @@ -29,7 +29,7 @@ \example itemviews/fetchmore \title Fetch More Example \ingroup examples-itemviews - \brief The Fetch More example shows how two add items to an item view + \brief The Fetch More example shows how to add items to an item view model on demand. \image fetchmore-example.png -- cgit v1.2.3 From 8c04aab8966611e96c64f469b7a1c6afe67e3fca Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 14:17:38 +0100 Subject: Cleanup Widgets examples - new signal/slot syntax Cleanup the Widget examples - use the new signal/slot syntax where possible - layout, statemachine, tools and touch subdirectory Change-Id: I466b309b643ef7ffc27be7591fa10f4c75cfd3f8 Reviewed-by: Luca Beldi Reviewed-by: Sze Howe Koh Reviewed-by: Paul Wicking --- examples/widgets/layouts/basiclayouts/dialog.cpp | 6 +-- examples/widgets/statemachine/factorial/main.cpp | 4 +- examples/widgets/statemachine/rogue/window.cpp | 3 +- .../widgets/statemachine/trafficlight/main.cpp | 16 +++---- .../widgets/statemachine/twowaybutton/main.cpp | 4 +- examples/widgets/tools/completer/mainwindow.cpp | 20 +++++---- .../widgets/tools/customcompleter/mainwindow.cpp | 6 +-- .../widgets/tools/customcompleter/textedit.cpp | 4 +- examples/widgets/tools/regexp/regexpdialog.cpp | 18 ++++---- .../tools/treemodelcompleter/mainwindow.cpp | 26 +++++------ examples/widgets/tools/undo/mainwindow.cpp | 50 +++++++++++----------- .../widgets/tools/undoframework/mainwindow.cpp | 22 +++++----- examples/widgets/touch/fingerpaint/mainwindow.cpp | 16 +++---- 13 files changed, 101 insertions(+), 94 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/layouts/basiclayouts/dialog.cpp b/examples/widgets/layouts/basiclayouts/dialog.cpp index 7acbc50eb7..8376820545 100644 --- a/examples/widgets/layouts/basiclayouts/dialog.cpp +++ b/examples/widgets/layouts/basiclayouts/dialog.cpp @@ -69,8 +69,8 @@ Dialog::Dialog() buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); //! [1] //! [2] @@ -99,7 +99,7 @@ void Dialog::createMenu() exitAction = fileMenu->addAction(tr("E&xit")); menuBar->addMenu(fileMenu); - connect(exitAction, SIGNAL(triggered()), this, SLOT(accept())); + connect(exitAction, &QAction::triggered, this, &QDialog::accept); } //! [6] diff --git a/examples/widgets/statemachine/factorial/main.cpp b/examples/widgets/statemachine/factorial/main.cpp index f100aa0110..2d25822828 100644 --- a/examples/widgets/statemachine/factorial/main.cpp +++ b/examples/widgets/statemachine/factorial/main.cpp @@ -100,7 +100,7 @@ class FactorialLoopTransition : public QSignalTransition { public: FactorialLoopTransition(Factorial *fact) - : QSignalTransition(fact, SIGNAL(xChanged(int))), m_fact(fact) + : QSignalTransition(fact, &Factorial::xChanged), m_fact(fact) {} bool eventTest(QEvent *e) override @@ -130,7 +130,7 @@ class FactorialDoneTransition : public QSignalTransition { public: FactorialDoneTransition(Factorial *fact) - : QSignalTransition(fact, SIGNAL(xChanged(int))), m_fact(fact) + : QSignalTransition(fact, &Factorial::xChanged), m_fact(fact) {} bool eventTest(QEvent *e) override diff --git a/examples/widgets/statemachine/rogue/window.cpp b/examples/widgets/statemachine/rogue/window.cpp index 059fbf1003..f91a6e522e 100644 --- a/examples/widgets/statemachine/rogue/window.cpp +++ b/examples/widgets/statemachine/rogue/window.cpp @@ -217,7 +217,8 @@ void Window::buildMachine() //![5] machine->setInitialState(inputState); - connect(machine, SIGNAL(finished()), qApp, SLOT(quit())); + connect(machine, &QStateMachine::finished, + qApp, &QApplication::quit); machine->start(); } diff --git a/examples/widgets/statemachine/trafficlight/main.cpp b/examples/widgets/statemachine/trafficlight/main.cpp index 21df91d8b0..b348d4f65d 100644 --- a/examples/widgets/statemachine/trafficlight/main.cpp +++ b/examples/widgets/statemachine/trafficlight/main.cpp @@ -132,11 +132,11 @@ QState *createLightState(LightWidget *light, int duration, QState *parent = 0) timer->setInterval(duration); timer->setSingleShot(true); QState *timing = new QState(lightState); - QObject::connect(timing, SIGNAL(entered()), light, SLOT(turnOn())); - QObject::connect(timing, SIGNAL(entered()), timer, SLOT(start())); - QObject::connect(timing, SIGNAL(exited()), light, SLOT(turnOff())); + QObject::connect(timing, &QAbstractState::entered, light, &LightWidget::turnOn); + QObject::connect(timing, &QAbstractState::entered, timer, QOverload<>::of(&QTimer::start)); + QObject::connect(timing, &QAbstractState::exited, light, &LightWidget::turnOff); QFinalState *done = new QFinalState(lightState); - timing->addTransition(timer, SIGNAL(timeout()), done); + timing->addTransition(timer, &QTimer::timeout, done); lightState->setInitialState(timing); return lightState; } @@ -159,14 +159,14 @@ public: redGoingYellow->setObjectName("redGoingYellow"); QState *yellowGoingGreen = createLightState(widget->yellowLight(), 1000); yellowGoingGreen->setObjectName("yellowGoingGreen"); - redGoingYellow->addTransition(redGoingYellow, SIGNAL(finished()), yellowGoingGreen); + redGoingYellow->addTransition(redGoingYellow, &QState::finished, yellowGoingGreen); QState *greenGoingYellow = createLightState(widget->greenLight(), 3000); greenGoingYellow->setObjectName("greenGoingYellow"); - yellowGoingGreen->addTransition(yellowGoingGreen, SIGNAL(finished()), greenGoingYellow); + yellowGoingGreen->addTransition(yellowGoingGreen, &QState::finished, greenGoingYellow); QState *yellowGoingRed = createLightState(widget->yellowLight(), 1000); yellowGoingRed->setObjectName("yellowGoingRed"); - greenGoingYellow->addTransition(greenGoingYellow, SIGNAL(finished()), yellowGoingRed); - yellowGoingRed->addTransition(yellowGoingRed, SIGNAL(finished()), redGoingYellow); + greenGoingYellow->addTransition(greenGoingYellow, &QState::finished, yellowGoingRed); + yellowGoingRed->addTransition(yellowGoingRed, &QState::finished, redGoingYellow); machine->addState(redGoingYellow); machine->addState(yellowGoingGreen); diff --git a/examples/widgets/statemachine/twowaybutton/main.cpp b/examples/widgets/statemachine/twowaybutton/main.cpp index 5c778aba70..3d4fef3bbe 100644 --- a/examples/widgets/statemachine/twowaybutton/main.cpp +++ b/examples/widgets/statemachine/twowaybutton/main.cpp @@ -69,8 +69,8 @@ int main(int argc, char **argv) //! [1] //! [2] - off->addTransition(&button, SIGNAL(clicked()), on); - on->addTransition(&button, SIGNAL(clicked()), off); + off->addTransition(&button, &QAbstractButton::clicked, on); + on->addTransition(&button, &QAbstractButton::clicked, off); //! [2] //! [3] diff --git a/examples/widgets/tools/completer/mainwindow.cpp b/examples/widgets/tools/completer/mainwindow.cpp index 8eb2e60030..114ff0fd7c 100644 --- a/examples/widgets/tools/completer/mainwindow.cpp +++ b/examples/widgets/tools/completer/mainwindow.cpp @@ -102,10 +102,14 @@ MainWindow::MainWindow(QWidget *parent) contentsLabel = new QLabel; contentsLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - connect(modelCombo, SIGNAL(activated(int)), this, SLOT(changeModel())); - connect(modeCombo, SIGNAL(activated(int)), this, SLOT(changeMode(int))); - connect(caseCombo, SIGNAL(activated(int)), this, SLOT(changeCase(int))); - connect(maxVisibleSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeMaxVisible(int))); + connect(modelCombo, QOverload::of(&QComboBox::activated), + this, &MainWindow::changeModel); + connect(modeCombo, QOverload::of(&QComboBox::activated), + this, &MainWindow::changeMode); + connect(caseCombo, QOverload::of(&QComboBox::activated), + this, &MainWindow::changeCase); + connect(maxVisibleSpinBox, QOverload::of(&QSpinBox::valueChanged), + this, &MainWindow::changeMaxVisible); //! [2] //! [3] @@ -136,9 +140,9 @@ void MainWindow::createMenu() QAction *aboutAct = new QAction(tr("About"), this); QAction *aboutQtAct = new QAction(tr("About Qt"), this); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + connect(exitAction, &QAction::triggered, qApp, &QApplication::quit); + connect(aboutAct, &QAction::triggered, this, &MainWindow::about); + connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); QMenu* fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); @@ -271,7 +275,7 @@ void MainWindow::changeModel() changeCase(caseCombo->currentIndex()); completer->setWrapAround(wrapCheckBox->isChecked()); lineEdit->setCompleter(completer); - connect(wrapCheckBox, SIGNAL(clicked(bool)), completer, SLOT(setWrapAround(bool))); + connect(wrapCheckBox, &QAbstractButton::clicked, completer, &QCompleter::setWrapAround); } //! [14] diff --git a/examples/widgets/tools/customcompleter/mainwindow.cpp b/examples/widgets/tools/customcompleter/mainwindow.cpp index 7b9db708b9..39f5f39617 100644 --- a/examples/widgets/tools/customcompleter/mainwindow.cpp +++ b/examples/widgets/tools/customcompleter/mainwindow.cpp @@ -79,9 +79,9 @@ void MainWindow::createMenu() QAction *aboutAct = new QAction(tr("About"), this); QAction *aboutQtAct = new QAction(tr("About Qt"), this); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + connect(exitAction, &QAction::triggered, qApp, &QApplication::quit); + connect(aboutAct, &QAction::triggered, this, &MainWindow::about); + connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); QMenu* fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); diff --git a/examples/widgets/tools/customcompleter/textedit.cpp b/examples/widgets/tools/customcompleter/textedit.cpp index 5512e72843..d42f7b38bb 100644 --- a/examples/widgets/tools/customcompleter/textedit.cpp +++ b/examples/widgets/tools/customcompleter/textedit.cpp @@ -88,8 +88,8 @@ void TextEdit::setCompleter(QCompleter *completer) c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); - QObject::connect(c, SIGNAL(activated(QString)), - this, SLOT(insertCompletion(QString))); + QObject::connect(c, QOverload::of(&QCompleter::activated), + this, &TextEdit::insertCompletion); } //! [2] diff --git a/examples/widgets/tools/regexp/regexpdialog.cpp b/examples/widgets/tools/regexp/regexpdialog.cpp index 7b3fee5794..bf61d09974 100644 --- a/examples/widgets/tools/regexp/regexpdialog.cpp +++ b/examples/widgets/tools/regexp/regexpdialog.cpp @@ -135,15 +135,15 @@ RegExpDialog::RegExpDialog(QWidget *parent) } setLayout(mainLayout); - connect(patternComboBox, SIGNAL(editTextChanged(QString)), - this, SLOT(refresh())); - connect(textComboBox, SIGNAL(editTextChanged(QString)), - this, SLOT(refresh())); - connect(caseSensitiveCheckBox, SIGNAL(toggled(bool)), - this, SLOT(refresh())); - connect(minimalCheckBox, SIGNAL(toggled(bool)), this, SLOT(refresh())); - connect(syntaxComboBox, SIGNAL(currentIndexChanged(int)), - this, SLOT(refresh())); + connect(patternComboBox, &QComboBox::editTextChanged, + this, &RegExpDialog::refresh); + connect(textComboBox, &QComboBox::editTextChanged, + this, &RegExpDialog::refresh); + connect(caseSensitiveCheckBox, &QAbstractButton::toggled, + this, &RegExpDialog::refresh); + connect(minimalCheckBox, &QAbstractButton::toggled, this, &RegExpDialog::refresh); + connect(syntaxComboBox, QOverload::of(&QComboBox::currentIndexChanged), + this, &RegExpDialog::refresh); patternComboBox->addItem(tr("[A-Za-z_]+([A-Za-z_0-9]*)")); textComboBox->addItem(tr("(10 + delta4) * 32")); diff --git a/examples/widgets/tools/treemodelcompleter/mainwindow.cpp b/examples/widgets/tools/treemodelcompleter/mainwindow.cpp index 72b2fad833..dec3cb0496 100644 --- a/examples/widgets/tools/treemodelcompleter/mainwindow.cpp +++ b/examples/widgets/tools/treemodelcompleter/mainwindow.cpp @@ -61,8 +61,8 @@ MainWindow::MainWindow(QWidget *parent) completer = new TreeModelCompleter(this); completer->setModel(modelFromFile(":/resources/treemodel.txt")); completer->setSeparator(QLatin1String(".")); - QObject::connect(completer, SIGNAL(highlighted(QModelIndex)), - this, SLOT(highlight(QModelIndex))); + QObject::connect(completer, QOverload::of(&TreeModelCompleter::highlighted), + this, &MainWindow::highlight); QWidget *centralWidget = new QWidget; @@ -91,18 +91,18 @@ MainWindow::MainWindow(QWidget *parent) QLineEdit *separatorLineEdit = new QLineEdit; separatorLineEdit->setText(completer->separator()); - connect(separatorLineEdit, SIGNAL(textChanged(QString)), - completer, SLOT(setSeparator(QString))); + connect(separatorLineEdit, &QLineEdit::textChanged, + completer, &TreeModelCompleter::setSeparator); QCheckBox *wrapCheckBox = new QCheckBox; wrapCheckBox->setText(tr("Wrap around completions")); wrapCheckBox->setChecked(completer->wrapAround()); - connect(wrapCheckBox, SIGNAL(clicked(bool)), completer, SLOT(setWrapAround(bool))); + connect(wrapCheckBox, &QAbstractButton::clicked, completer, &QCompleter::setWrapAround); contentsLabel = new QLabel; contentsLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - connect(separatorLineEdit, SIGNAL(textChanged(QString)), - this, SLOT(updateContentsLabel(QString))); + connect(separatorLineEdit, &QLineEdit::textChanged, + this, &MainWindow::updateContentsLabel); treeView = new QTreeView; treeView->setModel(completer->model()); @@ -111,8 +111,10 @@ MainWindow::MainWindow(QWidget *parent) //! [1] //! [2] - connect(modeCombo, SIGNAL(activated(int)), this, SLOT(changeMode(int))); - connect(caseCombo, SIGNAL(activated(int)), this, SLOT(changeCase(int))); + connect(modeCombo, QOverload::of(&QComboBox::activated), + this, &MainWindow::changeMode); + connect(caseCombo, QOverload::of(&QComboBox::activated), + this, &MainWindow::changeMode); lineEdit = new QLineEdit; lineEdit->setCompleter(completer); @@ -145,9 +147,9 @@ void MainWindow::createMenu() QAction *aboutAct = new QAction(tr("About"), this); QAction *aboutQtAct = new QAction(tr("About Qt"), this); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + connect(exitAction, &QAction::triggered, qApp, &QApplication::quit); + connect(aboutAct, &QAction::triggered, this, &MainWindow::about); + connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); QMenu* fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); diff --git a/examples/widgets/tools/undo/mainwindow.cpp b/examples/widgets/tools/undo/mainwindow.cpp index 5976163f3f..118d604742 100644 --- a/examples/widgets/tools/undo/mainwindow.cpp +++ b/examples/widgets/tools/undo/mainwindow.cpp @@ -68,25 +68,25 @@ MainWindow::MainWindow(QWidget *parent) documentTabs->removeTab(0); delete w; - connect(actionOpen, SIGNAL(triggered()), this, SLOT(openDocument())); - connect(actionClose, SIGNAL(triggered()), this, SLOT(closeDocument())); - connect(actionNew, SIGNAL(triggered()), this, SLOT(newDocument())); - connect(actionSave, SIGNAL(triggered()), this, SLOT(saveDocument())); - connect(actionExit, SIGNAL(triggered()), this, SLOT(close())); - connect(actionRed, SIGNAL(triggered()), this, SLOT(setShapeColor())); - connect(actionGreen, SIGNAL(triggered()), this, SLOT(setShapeColor())); - connect(actionBlue, SIGNAL(triggered()), this, SLOT(setShapeColor())); - connect(actionAddCircle, SIGNAL(triggered()), this, SLOT(addShape())); - connect(actionAddRectangle, SIGNAL(triggered()), this, SLOT(addShape())); - connect(actionAddTriangle, SIGNAL(triggered()), this, SLOT(addShape())); - connect(actionRemoveShape, SIGNAL(triggered()), this, SLOT(removeShape())); - connect(actionAddRobot, SIGNAL(triggered()), this, SLOT(addRobot())); - connect(actionAddSnowman, SIGNAL(triggered()), this, SLOT(addSnowman())); - connect(actionAbout, SIGNAL(triggered()), this, SLOT(about())); - connect(actionAboutQt, SIGNAL(triggered()), this, SLOT(aboutQt())); - - connect(undoLimit, SIGNAL(valueChanged(int)), this, SLOT(updateActions())); - connect(documentTabs, SIGNAL(currentChanged(int)), this, SLOT(updateActions())); + connect(actionOpen, &QAction::triggered, this, &MainWindow::openDocument); + connect(actionClose, &QAction::triggered, this, &MainWindow::closeDocument); + connect(actionNew, &QAction::triggered, this, &MainWindow::newDocument); + connect(actionSave, &QAction::triggered, this, &MainWindow::saveDocument); + connect(actionExit, &QAction::triggered, this, &QWidget::close); + connect(actionRed, &QAction::triggered, this, &MainWindow::setShapeColor); + connect(actionGreen, &QAction::triggered, this, &MainWindow::setShapeColor); + connect(actionBlue, &QAction::triggered, this, &MainWindow::setShapeColor); + connect(actionAddCircle, &QAction::triggered, this, &MainWindow::addShape); + connect(actionAddRectangle, &QAction::triggered, this, &MainWindow::addShape); + connect(actionAddTriangle, &QAction::triggered, this, &MainWindow::addShape); + connect(actionRemoveShape, &QAction::triggered, this, &MainWindow::removeShape); + connect(actionAddRobot, &QAction::triggered, this, &MainWindow::addRobot); + connect(actionAddSnowman, &QAction::triggered, this, &MainWindow::addSnowman); + connect(actionAbout, &QAction::triggered, this, &MainWindow::about); + connect(actionAboutQt, &QAction::triggered, this, &MainWindow::aboutQt); + + connect(undoLimit, QOverload::of(&QSpinBox::valueChanged), this, &MainWindow::updateActions); + connect(documentTabs, &QTabWidget::currentChanged, this, &MainWindow::updateActions); actionOpen->setShortcut(QString("Ctrl+O")); actionClose->setShortcut(QString("Ctrl+W")); @@ -226,9 +226,9 @@ void MainWindow::addDocument(Document *doc) return; m_undoGroup->addStack(doc->undoStack()); documentTabs->addTab(doc, fixedWindowTitle(doc)); - connect(doc, SIGNAL(currentShapeChanged(QString)), this, SLOT(updateActions())); - connect(doc->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions())); - connect(doc->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions())); + connect(doc, &Document::currentShapeChanged, this, &MainWindow::updateActions); + connect(doc->undoStack(), &QUndoStack::indexChanged, this, &MainWindow::updateActions); + connect(doc->undoStack(), &QUndoStack::cleanChanged, this, &MainWindow::updateActions); setCurrentDocument(doc); } @@ -251,9 +251,9 @@ void MainWindow::removeDocument(Document *doc) documentTabs->removeTab(index); m_undoGroup->removeStack(doc->undoStack()); - disconnect(doc, SIGNAL(currentShapeChanged(QString)), this, SLOT(updateActions())); - disconnect(doc->undoStack(), SIGNAL(indexChanged(int)), this, SLOT(updateActions())); - disconnect(doc->undoStack(), SIGNAL(cleanChanged(bool)), this, SLOT(updateActions())); + disconnect(doc, &Document::currentShapeChanged, this, &MainWindow::updateActions); + disconnect(doc->undoStack(), &QUndoStack::indexChanged, this, &MainWindow::updateActions); + disconnect(doc->undoStack(), &QUndoStack::cleanChanged, this, &MainWindow::updateActions); if (documentTabs->count() == 0) { newDocument(); diff --git a/examples/widgets/tools/undoframework/mainwindow.cpp b/examples/widgets/tools/undoframework/mainwindow.cpp index b2f5405b73..e95d50d164 100644 --- a/examples/widgets/tools/undoframework/mainwindow.cpp +++ b/examples/widgets/tools/undoframework/mainwindow.cpp @@ -70,8 +70,8 @@ MainWindow::MainWindow() diagramScene->setBackgroundBrush(pixmapBrush); diagramScene->setSceneRect(QRect(0, 0, 500, 500)); - connect(diagramScene, SIGNAL(itemMoved(DiagramItem*,QPointF)), - this, SLOT(itemMoved(DiagramItem*,QPointF))); + connect(diagramScene, &DiagramScene::itemMoved, + this, &MainWindow::itemMoved); setWindowTitle("Undo Framework"); QGraphicsView *view = new QGraphicsView(diagramScene); @@ -95,18 +95,18 @@ void MainWindow::createActions() { deleteAction = new QAction(tr("&Delete Item"), this); deleteAction->setShortcut(tr("Del")); - connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteItem())); + connect(deleteAction, &QAction::triggered, this, &MainWindow::deleteItem); //! [2] //! [3] //! [3] //! [4] addBoxAction = new QAction(tr("Add &Box"), this); //! [4] addBoxAction->setShortcut(tr("Ctrl+O")); - connect(addBoxAction, SIGNAL(triggered()), this, SLOT(addBox())); + connect(addBoxAction, &QAction::triggered, this, &MainWindow::addBox); addTriangleAction = new QAction(tr("Add &Triangle"), this); addTriangleAction->setShortcut(tr("Ctrl+T")); - connect(addTriangleAction, SIGNAL(triggered()), this, SLOT(addTriangle())); + connect(addTriangleAction, &QAction::triggered, this, &MainWindow::addTriangle); //! [5] undoAction = undoStack->createUndoAction(this, tr("&Undo")); @@ -118,13 +118,13 @@ void MainWindow::createActions() exitAction = new QAction(tr("E&xit"), this); exitAction->setShortcuts(QKeySequence::Quit); - connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); + connect(exitAction, &QAction::triggered, this, &QWidget::close); aboutAction = new QAction(tr("&About"), this); QList aboutShortcuts; aboutShortcuts << tr("Ctrl+A") << tr("Ctrl+B"); aboutAction->setShortcuts(aboutShortcuts); - connect(aboutAction, SIGNAL(triggered()), this, SLOT(about())); + connect(aboutAction, &QAction::triggered, this, &MainWindow::about); } //! [6] @@ -140,10 +140,10 @@ void MainWindow::createMenus() editMenu->addAction(redoAction); editMenu->addSeparator(); editMenu->addAction(deleteAction); - connect(editMenu, SIGNAL(aboutToShow()), - this, SLOT(itemMenuAboutToShow())); - connect(editMenu, SIGNAL(aboutToHide()), - this, SLOT(itemMenuAboutToHide())); + connect(editMenu, &QMenu::aboutToShow, + this, &MainWindow::itemMenuAboutToShow); + connect(editMenu, &QMenu::aboutToHide, + this, &MainWindow::itemMenuAboutToHide); //! [7] itemMenu = menuBar()->addMenu(tr("&Item")); diff --git a/examples/widgets/touch/fingerpaint/mainwindow.cpp b/examples/widgets/touch/fingerpaint/mainwindow.cpp index 0e45eea240..b0d91d25bf 100644 --- a/examples/widgets/touch/fingerpaint/mainwindow.cpp +++ b/examples/widgets/touch/fingerpaint/mainwindow.cpp @@ -127,34 +127,34 @@ void MainWindow::createActions() { openAct = new QAction(tr("&Open..."), this); openAct->setShortcut(tr("Ctrl+O")); - connect(openAct, SIGNAL(triggered()), this, SLOT(open())); + connect(openAct, &QAction::triggered, this, &MainWindow::open); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); - connect(action, SIGNAL(triggered()), this, SLOT(save())); + connect(action, &QAction::triggered, this, &MainWindow::save); saveAsActs.append(action); } printAct = new QAction(tr("&Print..."), this); - connect(printAct, SIGNAL(triggered()), scribbleArea, SLOT(print())); + connect(printAct, &QAction::triggered, scribbleArea, &ScribbleArea::print); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcut(tr("Ctrl+Q")); - connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); + connect(exitAct, &QAction::triggered, this, &QWidget::close); clearScreenAct = new QAction(tr("&Clear Screen"), this); clearScreenAct->setShortcut(tr("Ctrl+L")); - connect(clearScreenAct, SIGNAL(triggered()), - scribbleArea, SLOT(clearImage())); + connect(clearScreenAct, &QAction::triggered, + scribbleArea, &ScribbleArea::clearImage); aboutAct = new QAction(tr("&About"), this); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); + connect(aboutAct, &QAction::triggered, this, &MainWindow::about); aboutQtAct = new QAction(tr("About &Qt"), this); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); } //! [14] -- cgit v1.2.3 From a21f3431b861b09a4768801f856d431c6ac44313 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 14:14:13 +0100 Subject: Cleanup Widgets examples - new signal/slot syntax Cleanup the Widget examples - use the new signal/slot syntax where possible - tutorials subdirectory Change-Id: I741589f6616578412ad74f8371e0e3c87df783a2 Reviewed-by: Sze Howe Koh Reviewed-by: Luca Beldi --- .../tutorials/addressbook/part2/addressbook.cpp | 9 ++++-- .../tutorials/addressbook/part3/addressbook.cpp | 16 +++++++---- .../tutorials/addressbook/part4/addressbook.cpp | 21 +++++++++----- .../tutorials/addressbook/part5/addressbook.cpp | 24 ++++++++++------ .../tutorials/addressbook/part5/finddialog.cpp | 6 ++-- .../tutorials/addressbook/part6/addressbook.cpp | 30 +++++++++++++------- .../tutorials/addressbook/part6/finddialog.cpp | 6 ++-- .../tutorials/addressbook/part7/addressbook.cpp | 33 ++++++++++++++-------- .../tutorials/addressbook/part7/finddialog.cpp | 6 ++-- .../tutorials/gettingStarted/gsQt/part2/main.cpp | 3 +- .../tutorials/gettingStarted/gsQt/part3/main.cpp | 3 +- .../tutorials/gettingStarted/gsQt/part4/main.cpp | 10 ++++--- .../tutorials/gettingStarted/gsQt/part5/main.cpp | 10 ++++--- 13 files changed, 116 insertions(+), 61 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/tutorials/addressbook/part2/addressbook.cpp b/examples/widgets/tutorials/addressbook/part2/addressbook.cpp index 34fa5d2060..d5ee394abd 100644 --- a/examples/widgets/tutorials/addressbook/part2/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part2/addressbook.cpp @@ -74,9 +74,12 @@ AddressBook::AddressBook(QWidget *parent) cancelButton->hide(); //! [pushbutton declaration] //! [connecting signals and slots] - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); + connect(addButton, &QPushButton::clicked, + this, &AddressBook::addContact); + connect(submitButton, &QPushButton::clicked, + this, &AddressBook::submitContact); + connect(cancelButton, &QPushButton::clicked, + this, &AddressBook::cancel); //! [connecting signals and slots] //! [vertical layout] QVBoxLayout *buttonLayout1 = new QVBoxLayout; diff --git a/examples/widgets/tutorials/addressbook/part3/addressbook.cpp b/examples/widgets/tutorials/addressbook/part3/addressbook.cpp index caef83970a..b6d48f7a0d 100644 --- a/examples/widgets/tutorials/addressbook/part3/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part3/addressbook.cpp @@ -74,13 +74,17 @@ AddressBook::AddressBook(QWidget *parent) previousButton = new QPushButton(tr("&Previous")); previousButton->setEnabled(false); //! [navigation pushbuttons] - - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); + connect(addButton, &QPushButton::clicked, + this, &AddressBook::addContact); + connect(submitButton, &QPushButton::clicked, + this, &AddressBook::submitContact); + connect(cancelButton, &QPushButton::clicked, + this, &AddressBook::cancel); //! [connecting navigation signals] - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); + connect(nextButton, &QPushButton::clicked, + this, &AddressBook::next); + connect(previousButton, &QPushButton::clicked, + this, &AddressBook::previous); //! [connecting navigation signals] QVBoxLayout *buttonLayout1 = new QVBoxLayout; diff --git a/examples/widgets/tutorials/addressbook/part4/addressbook.cpp b/examples/widgets/tutorials/addressbook/part4/addressbook.cpp index 92f0776727..77ce216c07 100644 --- a/examples/widgets/tutorials/addressbook/part4/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part4/addressbook.cpp @@ -79,15 +79,22 @@ AddressBook::AddressBook(QWidget *parent) previousButton = new QPushButton(tr("&Previous")); previousButton->setEnabled(false); - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); + connect(addButton, &QPushButton::clicked, + this, &AddressBook::addContact); + connect(submitButton, &QPushButton::clicked, + this, &AddressBook::submitContact); //! [connecting edit and remove] - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); + connect(editButton, &QPushButton::clicked, + this, &AddressBook::editContact); + connect(removeButton, &QPushButton::clicked, + this, &AddressBook::removeContact); //! [connecting edit and remove] - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); + connect(cancelButton, &QPushButton::clicked, + this, &AddressBook::cancel); + connect(nextButton, &QPushButton::clicked, + this, &AddressBook::next); + connect(previousButton, &QPushButton::clicked, + this, &AddressBook::previous); QVBoxLayout *buttonLayout1 = new QVBoxLayout; buttonLayout1->addWidget(addButton); diff --git a/examples/widgets/tutorials/addressbook/part5/addressbook.cpp b/examples/widgets/tutorials/addressbook/part5/addressbook.cpp index 6e09ec287d..5505a0e35c 100644 --- a/examples/widgets/tutorials/addressbook/part5/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part5/addressbook.cpp @@ -86,16 +86,24 @@ AddressBook::AddressBook(QWidget *parent) dialog = new FindDialog(this); //! [instantiating FindDialog] - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); + connect(addButton, &QPushButton::clicked, + this, &AddressBook::addContact); + connect(submitButton, &QPushButton::clicked, + this, &AddressBook::submitContact); + connect(editButton, &QPushButton::clicked, + this, &AddressBook::editContact); + connect(removeButton, &QPushButton::clicked, + this, &AddressBook::removeContact); + connect(cancelButton, &QPushButton::clicked, + this, &AddressBook::cancel); //! [signals and slots for find] - connect(findButton, SIGNAL(clicked()), this, SLOT(findContact())); + connect(findButton, &QPushButton::clicked, + this, &AddressBook::findContact); //! [signals and slots for find] - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); + connect(nextButton, &QPushButton::clicked, + this, &AddressBook::next); + connect(previousButton, &QPushButton::clicked, + this, &AddressBook::previous); QVBoxLayout *buttonLayout1 = new QVBoxLayout; buttonLayout1->addWidget(addButton); diff --git a/examples/widgets/tutorials/addressbook/part5/finddialog.cpp b/examples/widgets/tutorials/addressbook/part5/finddialog.cpp index b0d9a5e6e3..615b39d42f 100644 --- a/examples/widgets/tutorials/addressbook/part5/finddialog.cpp +++ b/examples/widgets/tutorials/addressbook/part5/finddialog.cpp @@ -68,8 +68,10 @@ FindDialog::FindDialog(QWidget *parent) setLayout(layout); setWindowTitle(tr("Find a Contact")); - connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); - connect(findButton, SIGNAL(clicked()), this, SLOT(accept())); + connect(findButton, &QPushButton::clicked, + this, &FindDialog::findClicked); + connect(findButton, &QPushButton::clicked, + this, &FindDialog::accept); } //! [constructor] //! [findClicked() function] diff --git a/examples/widgets/tutorials/addressbook/part6/addressbook.cpp b/examples/widgets/tutorials/addressbook/part6/addressbook.cpp index b2e361a45e..8e740cfffc 100644 --- a/examples/widgets/tutorials/addressbook/part6/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part6/addressbook.cpp @@ -92,16 +92,26 @@ AddressBook::AddressBook(QWidget *parent) dialog = new FindDialog(this); - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); - connect(findButton, SIGNAL(clicked()), this, SLOT(findContact())); - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); - connect(loadButton, SIGNAL(clicked()), this, SLOT(loadFromFile())); - connect(saveButton, SIGNAL(clicked()), this, SLOT(saveToFile())); + connect(addButton, &QPushButton::clicked, + this, &AddressBook::addContact); + connect(submitButton, &QPushButton::clicked, + this, &AddressBook::submitContact); + connect(editButton, &QPushButton::clicked, + this, &AddressBook::editContact); + connect(removeButton, &QPushButton::clicked, + this, &AddressBook::removeContact); + connect(cancelButton, &QPushButton::clicked, + this, &AddressBook::cancel); + connect(findButton, &QPushButton::clicked, + this, &AddressBook::findContact); + connect(nextButton, &QPushButton::clicked, + this, &AddressBook::next); + connect(previousButton, &QPushButton::clicked, + this, &AddressBook::previous); + connect(loadButton, &QPushButton::clicked, + this, &AddressBook::loadFromFile); + connect(saveButton, &QPushButton::clicked, + this, &AddressBook::saveToFile); QVBoxLayout *buttonLayout1 = new QVBoxLayout; buttonLayout1->addWidget(addButton); diff --git a/examples/widgets/tutorials/addressbook/part6/finddialog.cpp b/examples/widgets/tutorials/addressbook/part6/finddialog.cpp index 6a1e6b116f..c25cccd552 100644 --- a/examples/widgets/tutorials/addressbook/part6/finddialog.cpp +++ b/examples/widgets/tutorials/addressbook/part6/finddialog.cpp @@ -67,8 +67,10 @@ FindDialog::FindDialog(QWidget *parent) setLayout(layout); setWindowTitle(tr("Find a Contact")); - connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); - connect(findButton, SIGNAL(clicked()), this, SLOT(accept())); + connect(findButton, &QPushButton::clicked, + this, &FindDialog::findClicked); + connect(findButton, &QPushButton::clicked, + this, &FindDialog::accept); } void FindDialog::findClicked() diff --git a/examples/widgets/tutorials/addressbook/part7/addressbook.cpp b/examples/widgets/tutorials/addressbook/part7/addressbook.cpp index e946c873e3..717d0882af 100644 --- a/examples/widgets/tutorials/addressbook/part7/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part7/addressbook.cpp @@ -92,17 +92,28 @@ AddressBook::AddressBook(QWidget *parent) dialog = new FindDialog(this); - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); - connect(findButton, SIGNAL(clicked()), this, SLOT(findContact())); - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); - connect(loadButton, SIGNAL(clicked()), this, SLOT(loadFromFile())); - connect(saveButton, SIGNAL(clicked()), this, SLOT(saveToFile())); - connect(exportButton, SIGNAL(clicked()), this, SLOT(exportAsVCard())); + connect(addButton, &QPushButton::clicked, + this, &AddressBook::addContact); + connect(submitButton, &QPushButton::clicked, + this, &AddressBook::submitContact); + connect(editButton, &QPushButton::clicked, + this, &AddressBook::editContact); + connect(removeButton, &QPushButton::clicked, + this, &AddressBook::removeContact); + connect(cancelButton, &QPushButton::clicked, + this, &AddressBook::cancel); + connect(findButton, &QPushButton::clicked, + this, &AddressBook::findContact); + connect(nextButton, &QPushButton::clicked, + this, &AddressBook::next); + connect(previousButton, &QPushButton::clicked, + this, &AddressBook::previous); + connect(loadButton, &QPushButton::clicked, + this, &AddressBook::loadFromFile); + connect(saveButton, &QPushButton::clicked, + this, &AddressBook::saveToFile); + connect(exportButton, &QPushButton::clicked, + this, &AddressBook::exportAsVCard); QVBoxLayout *buttonLayout1 = new QVBoxLayout; buttonLayout1->addWidget(addButton); diff --git a/examples/widgets/tutorials/addressbook/part7/finddialog.cpp b/examples/widgets/tutorials/addressbook/part7/finddialog.cpp index 6a1e6b116f..c25cccd552 100644 --- a/examples/widgets/tutorials/addressbook/part7/finddialog.cpp +++ b/examples/widgets/tutorials/addressbook/part7/finddialog.cpp @@ -67,8 +67,10 @@ FindDialog::FindDialog(QWidget *parent) setLayout(layout); setWindowTitle(tr("Find a Contact")); - connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); - connect(findButton, SIGNAL(clicked()), this, SLOT(accept())); + connect(findButton, &QPushButton::clicked, + this, &FindDialog::findClicked); + connect(findButton, &QPushButton::clicked, + this, &FindDialog::accept); } void FindDialog::findClicked() diff --git a/examples/widgets/tutorials/gettingStarted/gsQt/part2/main.cpp b/examples/widgets/tutorials/gettingStarted/gsQt/part2/main.cpp index 90f5f1a6b3..8bf83859a0 100644 --- a/examples/widgets/tutorials/gettingStarted/gsQt/part2/main.cpp +++ b/examples/widgets/tutorials/gettingStarted/gsQt/part2/main.cpp @@ -57,7 +57,8 @@ int main(int argc, char *argv[]) QTextEdit *textEdit = new QTextEdit; QPushButton *quitButton = new QPushButton("&Quit"); - QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); + QObject::connect(quitButton, &QPushButton::clicked, + qApp, &QApplication::quit); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(textEdit); diff --git a/examples/widgets/tutorials/gettingStarted/gsQt/part3/main.cpp b/examples/widgets/tutorials/gettingStarted/gsQt/part3/main.cpp index 0a60c1cf16..d4b43eb034 100644 --- a/examples/widgets/tutorials/gettingStarted/gsQt/part3/main.cpp +++ b/examples/widgets/tutorials/gettingStarted/gsQt/part3/main.cpp @@ -71,7 +71,8 @@ Notepad::Notepad() textEdit = new QTextEdit; quitButton = new QPushButton(tr("Quit")); - connect(quitButton, SIGNAL(clicked()), this, SLOT(quit())); + connect(quitButton, &QPushButton::clicked, + this, &Notepad::quit); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(textEdit); diff --git a/examples/widgets/tutorials/gettingStarted/gsQt/part4/main.cpp b/examples/widgets/tutorials/gettingStarted/gsQt/part4/main.cpp index 6d9e96a3d4..8c5fbc70ca 100644 --- a/examples/widgets/tutorials/gettingStarted/gsQt/part4/main.cpp +++ b/examples/widgets/tutorials/gettingStarted/gsQt/part4/main.cpp @@ -73,14 +73,16 @@ private: Notepad::Notepad() { - loadAction = new QAction(tr("&Load"), this); saveAction = new QAction(tr("&Save"), this); exitAction = new QAction(tr("E&xit"), this); - connect(loadAction, SIGNAL(triggered()), this, SLOT(load())); - connect(saveAction, SIGNAL(triggered()), this, SLOT(save())); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + connect(loadAction, &QAction::triggered, + this, &Notepad::load); + connect(saveAction, &QAction::triggered, + this, &Notepad::save); + connect(exitAction, &QAction::triggered, + qApp, &QApplication::quit); fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(loadAction); diff --git a/examples/widgets/tutorials/gettingStarted/gsQt/part5/main.cpp b/examples/widgets/tutorials/gettingStarted/gsQt/part5/main.cpp index b2b4a73874..cc3e1a261c 100644 --- a/examples/widgets/tutorials/gettingStarted/gsQt/part5/main.cpp +++ b/examples/widgets/tutorials/gettingStarted/gsQt/part5/main.cpp @@ -73,14 +73,16 @@ private: Notepad::Notepad() { - openAction = new QAction(tr("&Load"), this); saveAction = new QAction(tr("&Save"), this); exitAction = new QAction(tr("E&xit"), this); - connect(openAction, SIGNAL(triggered()), this, SLOT(open())); - connect(saveAction, SIGNAL(triggered()), this, SLOT(save())); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + connect(openAction, &QAction::triggered, + this, &Notepad::open); + connect(saveAction, &QAction::triggered, + this, &Notepad::save); + connect(exitAction, &QAction::triggered, + qApp, &QApplication::quit); fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAction); -- cgit v1.2.3 From cf27d9e8a5e14ebe083f4b0fa2204d0646e7ed5e Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 14:17:02 +0100 Subject: Cleanup Widgets examples - new signal/slot syntax MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cleanup the Widget examples - use the new signal/slot syntax where possible - painting and richtext subdirectory Change-Id: If0e365ab1cabf9184076595494cfca151406fddf Reviewed-by: Luca Beldi Reviewed-by: Topi Reiniö --- examples/widgets/painting/basicdrawing/window.cpp | 32 +++++------ .../widgets/painting/composition/composition.cpp | 62 +++++++++++----------- .../widgets/painting/concentriccircles/window.cpp | 4 +- examples/widgets/painting/deform/pathdeform.cpp | 43 ++++++++------- .../widgets/painting/fontsampler/mainwindow.cpp | 15 +++--- examples/widgets/painting/gradients/gradients.cpp | 2 +- .../painting/imagecomposition/imagecomposer.cpp | 9 ++-- examples/widgets/painting/painterpaths/window.cpp | 42 +++++++++------ .../widgets/painting/pathstroke/pathstroke.cpp | 56 +++++++++---------- examples/widgets/painting/shared/hoverpoints.cpp | 4 +- .../widgets/painting/transformations/window.cpp | 7 +-- examples/widgets/richtext/calendar/mainwindow.cpp | 10 ++-- examples/widgets/richtext/orderform/mainwindow.cpp | 2 +- .../richtext/syntaxhighlighter/mainwindow.cpp | 13 +++-- 14 files changed, 161 insertions(+), 140 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/painting/basicdrawing/window.cpp b/examples/widgets/painting/basicdrawing/window.cpp index c80237e914..65f6971d13 100644 --- a/examples/widgets/painting/basicdrawing/window.cpp +++ b/examples/widgets/painting/basicdrawing/window.cpp @@ -157,22 +157,22 @@ Window::Window() //! [7] //! [8] - connect(shapeComboBox, SIGNAL(activated(int)), - this, SLOT(shapeChanged())); - connect(penWidthSpinBox, SIGNAL(valueChanged(int)), - this, SLOT(penChanged())); - connect(penStyleComboBox, SIGNAL(activated(int)), - this, SLOT(penChanged())); - connect(penCapComboBox, SIGNAL(activated(int)), - this, SLOT(penChanged())); - connect(penJoinComboBox, SIGNAL(activated(int)), - this, SLOT(penChanged())); - connect(brushStyleComboBox, SIGNAL(activated(int)), - this, SLOT(brushChanged())); - connect(antialiasingCheckBox, SIGNAL(toggled(bool)), - renderArea, SLOT(setAntialiased(bool))); - connect(transformationsCheckBox, SIGNAL(toggled(bool)), - renderArea, SLOT(setTransformed(bool))); + connect(shapeComboBox, QOverload::of(&QComboBox::activated), + this, &Window::shapeChanged); + connect(penWidthSpinBox, QOverload::of(&QSpinBox::valueChanged), + this, &Window::penChanged); + connect(penStyleComboBox, QOverload::of(&QComboBox::activated), + this, &Window::penChanged); + connect(penCapComboBox, QOverload::of(&QComboBox::activated), + this, &Window::penChanged); + connect(penJoinComboBox, QOverload::of(&QComboBox::activated), + this, &Window::penChanged); + connect(brushStyleComboBox, QOverload::of(&QComboBox::activated), + this, &Window::brushChanged); + connect(antialiasingCheckBox, &QAbstractButton::toggled, + renderArea, &RenderArea::setAntialiased); + connect(transformationsCheckBox, &QAbstractButton::toggled, + renderArea, &RenderArea::setTransformed); //! [8] //! [9] diff --git a/examples/widgets/painting/composition/composition.cpp b/examples/widgets/painting/composition/composition.cpp index e0abc5875c..96088cca4a 100644 --- a/examples/widgets/painting/composition/composition.cpp +++ b/examples/widgets/painting/composition/composition.cpp @@ -76,68 +76,68 @@ CompositionWidget::CompositionWidget(QWidget *parent) modesGroup->setTitle(tr("Mode")); rbClear = new QRadioButton(tr("Clear"), modesGroup); - connect(rbClear, SIGNAL(clicked()), view, SLOT(setClearMode())); + connect(rbClear, &QAbstractButton::clicked, view, &CompositionRenderer::setClearMode); rbSource = new QRadioButton(tr("Source"), modesGroup); - connect(rbSource, SIGNAL(clicked()), view, SLOT(setSourceMode())); + connect(rbSource, &QAbstractButton::clicked, view, &CompositionRenderer::setSourceMode); rbDest = new QRadioButton(tr("Destination"), modesGroup); - connect(rbDest, SIGNAL(clicked()), view, SLOT(setDestMode())); + connect(rbDest, &QAbstractButton::clicked, view, &CompositionRenderer::setDestMode); rbSourceOver = new QRadioButton(tr("Source Over"), modesGroup); - connect(rbSourceOver, SIGNAL(clicked()), view, SLOT(setSourceOverMode())); + connect(rbSourceOver, &QAbstractButton::clicked, view, &CompositionRenderer::setSourceOverMode); rbDestOver = new QRadioButton(tr("Destination Over"), modesGroup); - connect(rbDestOver, SIGNAL(clicked()), view, SLOT(setDestOverMode())); + connect(rbDestOver, &QAbstractButton::clicked, view, &CompositionRenderer::setDestOverMode); rbSourceIn = new QRadioButton(tr("Source In"), modesGroup); - connect(rbSourceIn, SIGNAL(clicked()), view, SLOT(setSourceInMode())); + connect(rbSourceIn, &QAbstractButton::clicked, view, &CompositionRenderer::setSourceInMode); rbDestIn = new QRadioButton(tr("Dest In"), modesGroup); - connect(rbDestIn, SIGNAL(clicked()), view, SLOT(setDestInMode())); + connect(rbDestIn, &QAbstractButton::clicked, view, &CompositionRenderer::setDestInMode); rbSourceOut = new QRadioButton(tr("Source Out"), modesGroup); - connect(rbSourceOut, SIGNAL(clicked()), view, SLOT(setSourceOutMode())); + connect(rbSourceOut, &QAbstractButton::clicked, view, &CompositionRenderer::setSourceOutMode); rbDestOut = new QRadioButton(tr("Dest Out"), modesGroup); - connect(rbDestOut, SIGNAL(clicked()), view, SLOT(setDestOutMode())); + connect(rbDestOut, &QAbstractButton::clicked, view, &CompositionRenderer::setDestOutMode); rbSourceAtop = new QRadioButton(tr("Source Atop"), modesGroup); - connect(rbSourceAtop, SIGNAL(clicked()), view, SLOT(setSourceAtopMode())); + connect(rbSourceAtop, &QAbstractButton::clicked, view, &CompositionRenderer::setSourceAtopMode); rbDestAtop = new QRadioButton(tr("Dest Atop"), modesGroup); - connect(rbDestAtop, SIGNAL(clicked()), view, SLOT(setDestAtopMode())); + connect(rbDestAtop, &QAbstractButton::clicked, view, &CompositionRenderer::setDestAtopMode); rbXor = new QRadioButton(tr("Xor"), modesGroup); - connect(rbXor, SIGNAL(clicked()), view, SLOT(setXorMode())); + connect(rbXor, &QAbstractButton::clicked, view, &CompositionRenderer::setXorMode); rbPlus = new QRadioButton(tr("Plus"), modesGroup); - connect(rbPlus, SIGNAL(clicked()), view, SLOT(setPlusMode())); + connect(rbPlus, &QAbstractButton::clicked, view, &CompositionRenderer::setPlusMode); rbMultiply = new QRadioButton(tr("Multiply"), modesGroup); - connect(rbMultiply, SIGNAL(clicked()), view, SLOT(setMultiplyMode())); + connect(rbMultiply, &QAbstractButton::clicked, view, &CompositionRenderer::setMultiplyMode); rbScreen = new QRadioButton(tr("Screen"), modesGroup); - connect(rbScreen, SIGNAL(clicked()), view, SLOT(setScreenMode())); + connect(rbScreen, &QAbstractButton::clicked, view, &CompositionRenderer::setScreenMode); rbOverlay = new QRadioButton(tr("Overlay"), modesGroup); - connect(rbOverlay, SIGNAL(clicked()), view, SLOT(setOverlayMode())); + connect(rbOverlay, &QAbstractButton::clicked, view, &CompositionRenderer::setOverlayMode); rbDarken = new QRadioButton(tr("Darken"), modesGroup); - connect(rbDarken, SIGNAL(clicked()), view, SLOT(setDarkenMode())); + connect(rbDarken, &QAbstractButton::clicked, view, &CompositionRenderer::setDarkenMode); rbLighten = new QRadioButton(tr("Lighten"), modesGroup); - connect(rbLighten, SIGNAL(clicked()), view, SLOT(setLightenMode())); + connect(rbLighten, &QAbstractButton::clicked, view, &CompositionRenderer::setLightenMode); rbColorDodge = new QRadioButton(tr("Color Dodge"), modesGroup); - connect(rbColorDodge, SIGNAL(clicked()), view, SLOT(setColorDodgeMode())); + connect(rbColorDodge, &QAbstractButton::clicked, view, &CompositionRenderer::setColorDodgeMode); rbColorBurn = new QRadioButton(tr("Color Burn"), modesGroup); - connect(rbColorBurn, SIGNAL(clicked()), view, SLOT(setColorBurnMode())); + connect(rbColorBurn, &QAbstractButton::clicked, view, &CompositionRenderer::setColorBurnMode); rbHardLight = new QRadioButton(tr("Hard Light"), modesGroup); - connect(rbHardLight, SIGNAL(clicked()), view, SLOT(setHardLightMode())); + connect(rbHardLight, &QAbstractButton::clicked, view, &CompositionRenderer::setHardLightMode); rbSoftLight = new QRadioButton(tr("Soft Light"), modesGroup); - connect(rbSoftLight, SIGNAL(clicked()), view, SLOT(setSoftLightMode())); + connect(rbSoftLight, &QAbstractButton::clicked, view, &CompositionRenderer::setSoftLightMode); rbDifference = new QRadioButton(tr("Difference"), modesGroup); - connect(rbDifference, SIGNAL(clicked()), view, SLOT(setDifferenceMode())); + connect(rbDifference, &QAbstractButton::clicked, view, &CompositionRenderer::setDifferenceMode); rbExclusion = new QRadioButton(tr("Exclusion"), modesGroup); - connect(rbExclusion, SIGNAL(clicked()), view, SLOT(setExclusionMode())); + connect(rbExclusion, &QAbstractButton::clicked, view, &CompositionRenderer::setExclusionMode); QGroupBox *circleColorGroup = new QGroupBox(mainGroup); circleColorGroup->setTitle(tr("Circle color")); QSlider *circleColorSlider = new QSlider(Qt::Horizontal, circleColorGroup); circleColorSlider->setRange(0, 359); circleColorSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - connect(circleColorSlider, SIGNAL(valueChanged(int)), view, SLOT(setCircleColor(int))); + connect(circleColorSlider, &QAbstractSlider::valueChanged, view, &CompositionRenderer::setCircleColor); QGroupBox *circleAlphaGroup = new QGroupBox(mainGroup); circleAlphaGroup->setTitle(tr("Circle alpha")); QSlider *circleAlphaSlider = new QSlider(Qt::Horizontal, circleAlphaGroup); circleAlphaSlider->setRange(0, 255); circleAlphaSlider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - connect(circleAlphaSlider, SIGNAL(valueChanged(int)), view, SLOT(setCircleAlpha(int))); + connect(circleAlphaSlider, &QAbstractSlider::valueChanged, view, &CompositionRenderer::setCircleAlpha); QPushButton *showSourceButton = new QPushButton(mainGroup); showSourceButton->setText(tr("Show Source")); @@ -209,13 +209,13 @@ CompositionWidget::CompositionWidget(QWidget *parent) view->loadDescription(":res/composition/composition.html"); view->loadSourceFile(":res/composition/composition.cpp"); - connect(whatsThisButton, SIGNAL(clicked(bool)), view, SLOT(setDescriptionEnabled(bool))); - connect(view, SIGNAL(descriptionEnabledChanged(bool)), whatsThisButton, SLOT(setChecked(bool))); - connect(showSourceButton, SIGNAL(clicked()), view, SLOT(showSource())); + connect(whatsThisButton, &QAbstractButton::clicked, view, &ArthurFrame::setDescriptionEnabled); + connect(view, &ArthurFrame::descriptionEnabledChanged, whatsThisButton, &QAbstractButton::setChecked); + connect(showSourceButton, &QAbstractButton::clicked, view, &ArthurFrame::showSource); #if QT_CONFIG(opengl) - connect(enableOpenGLButton, SIGNAL(clicked(bool)), view, SLOT(enableOpenGL(bool))); + connect(enableOpenGLButton, &QAbstractButton::clicked, view, &ArthurFrame::enableOpenGL); #endif - connect(animateButton, SIGNAL(toggled(bool)), view, SLOT(setAnimationEnabled(bool))); + connect(animateButton, &QAbstractButton::toggled, view, &CompositionRenderer::setAnimationEnabled); circleColorSlider->setValue(270); circleAlphaSlider->setValue(200); diff --git a/examples/widgets/painting/concentriccircles/window.cpp b/examples/widgets/painting/concentriccircles/window.cpp index 0f65dc2285..45258e0bc4 100644 --- a/examples/widgets/painting/concentriccircles/window.cpp +++ b/examples/widgets/painting/concentriccircles/window.cpp @@ -77,8 +77,8 @@ Window::Window() circleWidgets[i][j]->setAntialiased(j != 0); circleWidgets[i][j]->setFloatBased(i != 0); - connect(timer, SIGNAL(timeout()), - circleWidgets[i][j], SLOT(nextAnimationFrame())); + connect(timer, &QTimer::timeout, + circleWidgets[i][j], &CircleWidget::nextAnimationFrame); layout->addWidget(circleWidgets[i][j], i + 1, j + 1); } diff --git a/examples/widgets/painting/deform/pathdeform.cpp b/examples/widgets/painting/deform/pathdeform.cpp index 7c3fe45277..3b80c40e9b 100644 --- a/examples/widgets/painting/deform/pathdeform.cpp +++ b/examples/widgets/painting/deform/pathdeform.cpp @@ -152,19 +152,19 @@ void PathDeformControls::layoutForDesktop() mainLayout->addWidget(mainGroup); mainLayout->setMargin(0); - connect(radiusSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setRadius(int))); - connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); - connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); - connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); + connect(radiusSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setRadius); + connect(deformSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setIntensity); + connect(fontSizeSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setFontSize); + connect(animateButton, &QAbstractButton::clicked, m_renderer, &PathDeformRenderer::setAnimated); #if QT_CONFIG(opengl) - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); + connect(enableOpenGLButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::enableOpenGL); #endif - connect(textInput, SIGNAL(textChanged(QString)), m_renderer, SLOT(setText(QString))); - connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), - whatsThisButton, SLOT(setChecked(bool))); - connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); - connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); + connect(textInput, &QLineEdit::textChanged, m_renderer, &PathDeformRenderer::setText); + connect(m_renderer, &ArthurFrame::descriptionEnabledChanged, + whatsThisButton, &QAbstractButton::setChecked); + connect(whatsThisButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::setDescriptionEnabled); + connect(showSourceButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::showSource); animateButton->animateClick(); deformSlider->setValue(80); @@ -229,14 +229,14 @@ void PathDeformControls::layoutForSmallScreen() mainLayout->addWidget(okButton); mainLayout->addWidget(quitButton); - connect(quitButton, SIGNAL(clicked()), this, SIGNAL(quitPressed())); - connect(okButton, SIGNAL(clicked()), this, SIGNAL(okPressed())); - connect(radiusSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setRadius(int))); - connect(deformSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setIntensity(int))); - connect(fontSizeSlider, SIGNAL(valueChanged(int)), m_renderer, SLOT(setFontSize(int))); - connect(animateButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setAnimated(bool))); + connect(quitButton, &QAbstractButton::clicked, this, &PathDeformControls::quitPressed); + connect(okButton, &QAbstractButton::clicked, this, &PathDeformControls::okPressed); + connect(radiusSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setRadius); + connect(deformSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setIntensity); + connect(fontSizeSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setFontSize); + connect(animateButton, &QAbstractButton::clicked, m_renderer, &PathDeformRenderer::setAnimated); #if QT_CONFIG(opengl) - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); + connect(enableOpenGLButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::enableOpenGL); #endif @@ -272,9 +272,12 @@ PathDeformWidget::PathDeformWidget(QWidget *parent, bool smallScreen) m_renderer->loadDescription(":res/deform/pathdeform.html"); m_renderer->setDescriptionEnabled(false); - connect(m_renderer, SIGNAL(clicked()), this, SLOT(showControls())); - connect(m_controls, SIGNAL(okPressed()), this, SLOT(hideControls())); - connect(m_controls, SIGNAL(quitPressed()), QCoreApplication::instance(), SLOT(quit())); + connect(m_renderer, &PathDeformRenderer::clicked, + this, &PathDeformWidget::showControls); + connect(m_controls, &PathDeformControls::okPressed, + this, &PathDeformWidget::hideControls); + connect(m_controls, &PathDeformControls::quitPressed, + qApp, &QCoreApplication::quit); } diff --git a/examples/widgets/painting/fontsampler/mainwindow.cpp b/examples/widgets/painting/fontsampler/mainwindow.cpp index bd15438df9..6344806f29 100644 --- a/examples/widgets/painting/fontsampler/mainwindow.cpp +++ b/examples/widgets/painting/fontsampler/mainwindow.cpp @@ -71,11 +71,12 @@ MainWindow::MainWindow(QWidget *parent) markedCount = 0; setupFontTree(); - connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - connect(fontTree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), - this, SLOT(showFont(QTreeWidgetItem*))); - connect(fontTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), - this, SLOT(updateStyles(QTreeWidgetItem*,int))); + connect(quitAction, &QAction::triggered, + qApp, &QApplication::quit); + connect(fontTree, &QTreeWidget::currentItemChanged, + this, &MainWindow::showFont); + connect(fontTree, &QTreeWidget::itemChanged, + this, &MainWindow::updateStyles); fontTree->setItemSelected(fontTree->topLevelItem(0), true); showFont(fontTree->topLevelItem(0)); @@ -285,8 +286,8 @@ void MainWindow::on_printPreviewAction_triggered() QPrinter printer(QPrinter::HighResolution); QPrintPreviewDialog preview(&printer, this); - connect(&preview, SIGNAL(paintRequested(QPrinter*)), - this, SLOT(printDocument(QPrinter*))); + connect(&preview, &QPrintPreviewDialog::paintRequested, + this, &MainWindow::printDocument); preview.exec(); #endif } diff --git a/examples/widgets/painting/gradients/gradients.cpp b/examples/widgets/painting/gradients/gradients.cpp index 004f6710cd..fd6eaeb0d9 100644 --- a/examples/widgets/painting/gradients/gradients.cpp +++ b/examples/widgets/painting/gradients/gradients.cpp @@ -421,7 +421,7 @@ GradientWidget::GradientWidget(QWidget *parent) m_renderer->loadSourceFile(":res/gradients/gradients.cpp"); m_renderer->loadDescription(":res/gradients/gradients.html"); - QTimer::singleShot(50, this, SLOT(setDefault1())); + QTimer::singleShot(50, this, &GradientWidget::setDefault1); } void GradientWidget::setDefault(int config) diff --git a/examples/widgets/painting/imagecomposition/imagecomposer.cpp b/examples/widgets/painting/imagecomposition/imagecomposer.cpp index d53017b955..ffdc8f433c 100644 --- a/examples/widgets/painting/imagecomposition/imagecomposer.cpp +++ b/examples/widgets/painting/imagecomposition/imagecomposer.cpp @@ -100,9 +100,12 @@ ImageComposer::ImageComposer() //! [2] //! [3] - connect(sourceButton, SIGNAL(clicked()), this, SLOT(chooseSource())); - connect(operatorComboBox, SIGNAL(activated(int)), this, SLOT(recalculateResult())); - connect(destinationButton, SIGNAL(clicked()), this, SLOT(chooseDestination())); + connect(sourceButton, &QAbstractButton::clicked, + this, &ImageComposer::chooseSource); + connect(operatorComboBox, QOverload::of(&QComboBox::activated), + this, &ImageComposer::recalculateResult); + connect(destinationButton, &QAbstractButton::clicked, + this, &ImageComposer::chooseDestination); //! [3] //! [4] diff --git a/examples/widgets/painting/painterpaths/window.cpp b/examples/widgets/painting/painterpaths/window.cpp index a987937b39..95e312623e 100644 --- a/examples/widgets/painting/painterpaths/window.cpp +++ b/examples/widgets/painting/painterpaths/window.cpp @@ -194,22 +194,30 @@ Window::Window() //! [12] //! [16] - connect(fillRuleComboBox, SIGNAL(activated(int)), this, SLOT(fillRuleChanged())); - connect(fillColor1ComboBox, SIGNAL(activated(int)), this, SLOT(fillGradientChanged())); - connect(fillColor2ComboBox, SIGNAL(activated(int)), this, SLOT(fillGradientChanged())); - connect(penColorComboBox, SIGNAL(activated(int)), this, SLOT(penColorChanged())); - - for(QList::iterator it = renderAreas.begin(); it != renderAreas.end(); it++) { - connect(penWidthSpinBox, SIGNAL(valueChanged(int)), *it, SLOT(setPenWidth(int))); - connect(rotationAngleSpinBox, SIGNAL(valueChanged(int)), *it, SLOT(setRotationAngle(int))); + connect(fillRuleComboBox, QOverload::of(&QComboBox::activated), + this, &Window::fillRuleChanged); + connect(fillColor1ComboBox, QOverload::of(&QComboBox::activated), + this, &Window::fillGradientChanged); + connect(fillColor2ComboBox, QOverload::of(&QComboBox::activated), + this, &Window::fillGradientChanged); + connect(penColorComboBox, QOverload::of(&QComboBox::activated), + this, &Window::penColorChanged); + + for (RenderArea *area : qAsConst(renderAreas)) { + connect(penWidthSpinBox, QOverload::of(&QSpinBox::valueChanged), + area, &RenderArea::setPenWidth); + connect(rotationAngleSpinBox, QOverload::of(&QSpinBox::valueChanged), + area, &RenderArea::setRotationAngle); } //! [16] //! [17] QGridLayout *topLayout = new QGridLayout; - int i=0; - for(QList::iterator it = renderAreas.begin(); it != renderAreas.end(); it++, i++) - topLayout->addWidget(*it, i / 3, i % 3); + int i = 0; + for (RenderArea *area : qAsConst(renderAreas)) { + topLayout->addWidget(area, i / 3, i % 3); + ++i; + } QGridLayout *mainLayout = new QGridLayout; mainLayout->addLayout(topLayout, 0, 0, 1, 4); @@ -243,8 +251,8 @@ void Window::fillRuleChanged() { Qt::FillRule rule = (Qt::FillRule)currentItemData(fillRuleComboBox).toInt(); - for (QList::iterator it = renderAreas.begin(); it != renderAreas.end(); ++it) - (*it)->setFillRule(rule); + for (RenderArea *area : qAsConst(renderAreas)) + area->setFillRule(rule); } //! [19] @@ -254,8 +262,8 @@ void Window::fillGradientChanged() QColor color1 = qvariant_cast(currentItemData(fillColor1ComboBox)); QColor color2 = qvariant_cast(currentItemData(fillColor2ComboBox)); - for (QList::iterator it = renderAreas.begin(); it != renderAreas.end(); ++it) - (*it)->setFillGradient(color1, color2); + for (RenderArea *area : qAsConst(renderAreas)) + area->setFillGradient(color1, color2); } //! [20] @@ -264,8 +272,8 @@ void Window::penColorChanged() { QColor color = qvariant_cast(currentItemData(penColorComboBox)); - for (QList::iterator it = renderAreas.begin(); it != renderAreas.end(); ++it) - (*it)->setPenColor(color); + for (RenderArea *area : qAsConst(renderAreas)) + area->setPenColor(color); } //! [21] diff --git a/examples/widgets/painting/pathstroke/pathstroke.cpp b/examples/widgets/painting/pathstroke/pathstroke.cpp index b04998afac..acb946496f 100644 --- a/examples/widgets/painting/pathstroke/pathstroke.cpp +++ b/examples/widgets/painting/pathstroke/pathstroke.cpp @@ -164,24 +164,24 @@ void PathStrokeControls::createCommonControls(QWidget* parent) // Connections - connect(flatCap, SIGNAL(clicked()), m_renderer, SLOT(setFlatCap())); - connect(squareCap, SIGNAL(clicked()), m_renderer, SLOT(setSquareCap())); - connect(roundCap, SIGNAL(clicked()), m_renderer, SLOT(setRoundCap())); + connect(flatCap, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setFlatCap); + connect(squareCap, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setSquareCap); + connect(roundCap, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setRoundCap); - connect(bevelJoin, SIGNAL(clicked()), m_renderer, SLOT(setBevelJoin())); - connect(miterJoin, SIGNAL(clicked()), m_renderer, SLOT(setMiterJoin())); - connect(svgMiterJoin, SIGNAL(clicked()), m_renderer, SLOT(setSvgMiterJoin())); - connect(roundJoin, SIGNAL(clicked()), m_renderer, SLOT(setRoundJoin())); + connect(bevelJoin, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setBevelJoin); + connect(miterJoin, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setMiterJoin); + connect(svgMiterJoin, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setSvgMiterJoin); + connect(roundJoin, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setRoundJoin); - connect(curveMode, SIGNAL(clicked()), m_renderer, SLOT(setCurveMode())); - connect(lineMode, SIGNAL(clicked()), m_renderer, SLOT(setLineMode())); + connect(curveMode, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setCurveMode); + connect(lineMode, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setLineMode); - connect(solidLine, SIGNAL(clicked()), m_renderer, SLOT(setSolidLine())); - connect(dashLine, SIGNAL(clicked()), m_renderer, SLOT(setDashLine())); - connect(dotLine, SIGNAL(clicked()), m_renderer, SLOT(setDotLine())); - connect(dashDotLine, SIGNAL(clicked()), m_renderer, SLOT(setDashDotLine())); - connect(dashDotDotLine, SIGNAL(clicked()), m_renderer, SLOT(setDashDotDotLine())); - connect(customDashLine, SIGNAL(clicked()), m_renderer, SLOT(setCustomDashLine())); + connect(solidLine, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setSolidLine); + connect(dashLine, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setDashLine); + connect(dotLine, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setDotLine); + connect(dashDotLine, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setDashDotLine); + connect(dashDotDotLine, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setDashDotDotLine); + connect(customDashLine, &QAbstractButton::clicked, m_renderer, &PathStrokeRenderer::setCustomDashLine); // Set the defaults: flatCap->setChecked(true); @@ -247,17 +247,17 @@ void PathStrokeControls::layoutForDesktop() // Set up connections - connect(animated, SIGNAL(toggled(bool)), m_renderer, SLOT(setAnimation(bool))); + connect(animated, &QAbstractButton::toggled, m_renderer, &PathStrokeRenderer::setAnimation); - connect(penWidth, SIGNAL(valueChanged(int)), m_renderer, SLOT(setPenWidth(int))); + connect(penWidth, &QAbstractSlider::valueChanged, m_renderer, &PathStrokeRenderer::setPenWidth); - connect(showSourceButton, SIGNAL(clicked()), m_renderer, SLOT(showSource())); + connect(showSourceButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::showSource); #if QT_CONFIG(opengl) - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); + connect(enableOpenGLButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::enableOpenGL); #endif - connect(whatsThisButton, SIGNAL(clicked(bool)), m_renderer, SLOT(setDescriptionEnabled(bool))); - connect(m_renderer, SIGNAL(descriptionEnabledChanged(bool)), - whatsThisButton, SLOT(setChecked(bool))); + connect(whatsThisButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::setDescriptionEnabled); + connect(m_renderer, &ArthurFrame::descriptionEnabledChanged, + whatsThisButton, &QAbstractButton::setChecked); // Set the defaults @@ -327,12 +327,12 @@ void PathStrokeControls::layoutForSmallScreens() mainLayout->addWidget(okBtn, 2, 2, Qt::AlignHCenter | Qt::AlignTop); #if QT_CONFIG(opengl) - connect(enableOpenGLButton, SIGNAL(clicked(bool)), m_renderer, SLOT(enableOpenGL(bool))); + connect(enableOpenGLButton, &QAbstractButton::clicked, m_renderer, &ArthurFrame::enableOpenGL); #endif - connect(penWidth, SIGNAL(valueChanged(int)), m_renderer, SLOT(setPenWidth(int))); - connect(quitBtn, SIGNAL(clicked()), this, SLOT(emitQuitSignal())); - connect(okBtn, SIGNAL(clicked()), this, SLOT(emitOkSignal())); + connect(penWidth, &QAbstractSlider::valueChanged, m_renderer, &PathStrokeRenderer::setPenWidth); + connect(quitBtn, &QAbstractButton::clicked, this, &PathStrokeControls::emitQuitSignal); + connect(okBtn, &QAbstractButton::clicked, this, &PathStrokeControls::emitOkSignal); m_renderer->setAnimation(true); penWidth->setValue(50); @@ -368,8 +368,8 @@ PathStrokeWidget::PathStrokeWidget(bool smallScreen) m_renderer->loadSourceFile(":res/pathstroke/pathstroke.cpp"); m_renderer->loadDescription(":res/pathstroke/pathstroke.html"); - connect(m_renderer, SIGNAL(clicked()), this, SLOT(showControls())); - connect(m_controls, SIGNAL(okPressed()), this, SLOT(hideControls())); + connect(m_renderer, &PathStrokeRenderer::clicked, this, &PathStrokeWidget::showControls); + connect(m_controls, &PathStrokeControls::okPressed, this, &PathStrokeWidget::hideControls); connect(m_controls, SIGNAL(quitPressed()), QApplication::instance(), SLOT(quit())); } diff --git a/examples/widgets/painting/shared/hoverpoints.cpp b/examples/widgets/painting/shared/hoverpoints.cpp index 7cd8cc0b29..a16bda4835 100644 --- a/examples/widgets/painting/shared/hoverpoints.cpp +++ b/examples/widgets/painting/shared/hoverpoints.cpp @@ -73,8 +73,8 @@ HoverPoints::HoverPoints(QWidget *widget, PointShape shape) m_editable = true; m_enabled = true; - connect(this, SIGNAL(pointsChanged(QPolygonF)), - m_widget, SLOT(update())); + connect(this, &HoverPoints::pointsChanged, + m_widget, QOverload<>::of(&QWidget::update)); } diff --git a/examples/widgets/painting/transformations/window.cpp b/examples/widgets/painting/transformations/window.cpp index d8babb2e00..8261c4e12e 100644 --- a/examples/widgets/painting/transformations/window.cpp +++ b/examples/widgets/painting/transformations/window.cpp @@ -79,8 +79,8 @@ Window::Window() operationComboBoxes[i]->addItem(tr("Scale to 75%")); operationComboBoxes[i]->addItem(tr("Translate by (50, 50)")); - connect(operationComboBoxes[i], SIGNAL(activated(int)), - this, SLOT(operationChanged())); + connect(operationComboBoxes[i], QOverload::of(&QComboBox::activated), + this, &Window::operationChanged); layout->addWidget(transformedRenderAreas[i], 0, i + 1); layout->addWidget(operationComboBoxes[i], 1, i + 1); @@ -159,7 +159,8 @@ void Window::setupShapes() shapes.append(text); shapes.append(truck); - connect(shapeComboBox, SIGNAL(activated(int)), this, SLOT(shapeSelected(int))); + connect(shapeComboBox, QOverload::of(&QComboBox::activated), + this, &Window::shapeSelected); } //! [7] diff --git a/examples/widgets/richtext/calendar/mainwindow.cpp b/examples/widgets/richtext/calendar/mainwindow.cpp index 38dc0e2849..3ddb1cf7ad 100644 --- a/examples/widgets/richtext/calendar/mainwindow.cpp +++ b/examples/widgets/richtext/calendar/mainwindow.cpp @@ -86,10 +86,12 @@ MainWindow::MainWindow() //! [2] //! [3] - connect(monthCombo, SIGNAL(activated(int)), this, SLOT(setMonth(int))); - connect(yearEdit, SIGNAL(dateChanged(QDate)), this, SLOT(setYear(QDate))); - connect(fontSizeSpinBox, SIGNAL(valueChanged(int)), - this, SLOT(setFontSize(int))); + connect(monthCombo, QOverload::of(&QComboBox::activated), + this, &MainWindow::setMonth); + connect(yearEdit, &QDateTimeEdit::dateChanged, + this, &MainWindow::setYear); + connect(fontSizeSpinBox, QOverload::of(&QSpinBox::valueChanged), + this, &MainWindow::setFontSize); //! [3] fontSizeSpinBox->setValue(10); diff --git a/examples/widgets/richtext/orderform/mainwindow.cpp b/examples/widgets/richtext/orderform/mainwindow.cpp index b207ee4dbc..291c37edf6 100644 --- a/examples/widgets/richtext/orderform/mainwindow.cpp +++ b/examples/widgets/richtext/orderform/mainwindow.cpp @@ -66,7 +66,7 @@ MainWindow::MainWindow() QMenu *fileMenu = new QMenu(tr("&File"), this); QAction *newAction = fileMenu->addAction(tr("&New...")); newAction->setShortcuts(QKeySequence::New); - printAction = fileMenu->addAction(tr("&Print..."), this, SLOT(printFile())); + printAction = fileMenu->addAction(tr("&Print..."), this, &MainWindow::printFile); printAction->setShortcuts(QKeySequence::Print); printAction->setEnabled(false); QAction *quitAction = fileMenu->addAction(tr("E&xit")); diff --git a/examples/widgets/richtext/syntaxhighlighter/mainwindow.cpp b/examples/widgets/richtext/syntaxhighlighter/mainwindow.cpp index dd58f1f45b..2dba0ba73e 100644 --- a/examples/widgets/richtext/syntaxhighlighter/mainwindow.cpp +++ b/examples/widgets/richtext/syntaxhighlighter/mainwindow.cpp @@ -117,9 +117,12 @@ void MainWindow::setupFileMenu() QMenu *fileMenu = new QMenu(tr("&File"), this); menuBar()->addMenu(fileMenu); - fileMenu->addAction(tr("&New"), this, SLOT(newFile()), QKeySequence::New); - fileMenu->addAction(tr("&Open..."), this, SLOT(openFile()), QKeySequence::Open); - fileMenu->addAction(tr("E&xit"), qApp, SLOT(quit()), QKeySequence::Quit); + fileMenu->addAction(tr("&New"), this, + &MainWindow::newFile, QKeySequence::New); + fileMenu->addAction(tr("&Open..."), + this, [this](){ openFile(); }, QKeySequence::Open); + fileMenu->addAction(tr("E&xit"), qApp, + &QApplication::quit, QKeySequence::Quit); } void MainWindow::setupHelpMenu() @@ -127,6 +130,6 @@ void MainWindow::setupHelpMenu() QMenu *helpMenu = new QMenu(tr("&Help"), this); menuBar()->addMenu(helpMenu); - helpMenu->addAction(tr("&About"), this, SLOT(about())); - helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); + helpMenu->addAction(tr("&About"), this, &MainWindow::about); + helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); } -- cgit v1.2.3 From 8cf812231405e011b422a1505d9a219618fe5cee Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 14:15:36 +0100 Subject: Cleanup Widgets examples - new signal/slot syntax MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cleanup the Widget examples - use the new signal/slot syntax where possible - animation, effects and graphicsview subdirectory Change-Id: I6cbaea6e628eb06f8e0ca6a0b795030a66b83878 Reviewed-by: Luca Beldi Reviewed-by: Topi Reiniö --- examples/widgets/animation/easing/window.cpp | 15 +++-- examples/widgets/animation/moveblocks/main.cpp | 4 +- examples/widgets/animation/states/main.cpp | 6 +- examples/widgets/animation/stickman/lifecycle.cpp | 16 +++--- examples/widgets/animation/stickman/stickman.cpp | 2 +- .../animation/sub-attaq/animationmanager.cpp | 4 +- examples/widgets/animation/sub-attaq/boat.cpp | 10 ++-- examples/widgets/animation/sub-attaq/bomb.cpp | 10 ++-- .../widgets/animation/sub-attaq/graphicsscene.cpp | 18 +++--- .../animation/sub-attaq/qanimationstate.cpp | 6 +- examples/widgets/animation/sub-attaq/states.cpp | 12 ++-- examples/widgets/animation/sub-attaq/submarine.cpp | 12 ++-- examples/widgets/animation/sub-attaq/submarine_p.h | 3 +- examples/widgets/animation/sub-attaq/torpedo.cpp | 10 ++-- .../widgets/effects/fademessage/fademessage.cpp | 2 +- examples/widgets/graphicsview/boxes/scene.cpp | 42 +++++++------- examples/widgets/graphicsview/chip/view.cpp | 32 +++++------ .../widgets/graphicsview/collidingmice/main.cpp | 2 +- .../graphicsview/diagramscene/diagramscene.cpp | 8 +-- .../graphicsview/diagramscene/mainwindow.cpp | 64 +++++++++++----------- .../graphicsview/embeddeddialogs/customproxy.cpp | 8 +-- 21 files changed, 148 insertions(+), 138 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/animation/easing/window.cpp b/examples/widgets/animation/easing/window.cpp index 8c03e0534d..aa12147388 100644 --- a/examples/widgets/animation/easing/window.cpp +++ b/examples/widgets/animation/easing/window.cpp @@ -66,11 +66,16 @@ Window::Window(QWidget *parent) m_ui.amplitudeSpinBox->setValue(dummy.amplitude()); m_ui.overshootSpinBox->setValue(dummy.overshoot()); - connect(m_ui.easingCurvePicker, SIGNAL(currentRowChanged(int)), this, SLOT(curveChanged(int))); - connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathChanged(int))); - connect(m_ui.periodSpinBox, SIGNAL(valueChanged(double)), this, SLOT(periodChanged(double))); - connect(m_ui.amplitudeSpinBox, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); - connect(m_ui.overshootSpinBox, SIGNAL(valueChanged(double)), this, SLOT(overshootChanged(double))); + connect(m_ui.easingCurvePicker, &QListWidget::currentRowChanged, + this, &Window::curveChanged); + connect(buttonGroup, QOverload::of(&QButtonGroup::buttonClicked), + this, &Window::pathChanged); + connect(m_ui.periodSpinBox, QOverload::of(&QDoubleSpinBox::valueChanged), + this, &Window::periodChanged); + connect(m_ui.amplitudeSpinBox, QOverload::of(&QDoubleSpinBox::valueChanged), + this, &Window::amplitudeChanged); + connect(m_ui.overshootSpinBox, QOverload::of(&QDoubleSpinBox::valueChanged), + this, &Window::overshootChanged); createCurveIcons(); QPixmap pix(QLatin1String(":/images/qt-logo.png")); diff --git a/examples/widgets/animation/moveblocks/main.cpp b/examples/widgets/animation/moveblocks/main.cpp index 6d17696108..e59b17cbf9 100644 --- a/examples/widgets/animation/moveblocks/main.cpp +++ b/examples/widgets/animation/moveblocks/main.cpp @@ -214,7 +214,7 @@ int main(int argc, char **argv) QTimer timer; timer.setInterval(1250); timer.setSingleShot(true); - QObject::connect(group, SIGNAL(entered()), &timer, SLOT(start())); + QObject::connect(group, &QState::entered, &timer, QOverload<>::of(&QTimer::start)); //![2] //![3] @@ -302,7 +302,7 @@ int main(int argc, char **argv) //![7] StateSwitcher *stateSwitcher = new StateSwitcher(&machine); stateSwitcher->setObjectName("stateSwitcher"); - group->addTransition(&timer, SIGNAL(timeout()), stateSwitcher); + group->addTransition(&timer, &QTimer::timeout, stateSwitcher); stateSwitcher->addState(state1, &animationGroup); stateSwitcher->addState(state2, &animationGroup); //![7] diff --git a/examples/widgets/animation/states/main.cpp b/examples/widgets/animation/states/main.cpp index 14d193c301..0f61b7457a 100644 --- a/examples/widgets/animation/states/main.cpp +++ b/examples/widgets/animation/states/main.cpp @@ -214,7 +214,7 @@ int main(int argc, char *argv[]) state3->assignProperty(p5, "opacity", qreal(1)); state3->assignProperty(p6, "opacity", qreal(1)); - QAbstractTransition *t1 = state1->addTransition(button, SIGNAL(clicked()), state2); + QAbstractTransition *t1 = state1->addTransition(button, &QAbstractButton::clicked, state2); QSequentialAnimationGroup *animation1SubGroup = new QSequentialAnimationGroup; animation1SubGroup->addPause(250); animation1SubGroup->addAnimation(new QPropertyAnimation(box, "geometry")); @@ -239,7 +239,7 @@ int main(int argc, char *argv[]) t1->addAnimation(new QPropertyAnimation(p5, "opacity")); t1->addAnimation(new QPropertyAnimation(p6, "opacity")); - QAbstractTransition *t2 = state2->addTransition(button, SIGNAL(clicked()), state3); + QAbstractTransition *t2 = state2->addTransition(button, &QAbstractButton::clicked, state3); t2->addAnimation(new QPropertyAnimation(box, "geometry")); t2->addAnimation(new QPropertyAnimation(widget, "geometry")); t2->addAnimation(new QPropertyAnimation(p1, "pos")); @@ -261,7 +261,7 @@ int main(int argc, char *argv[]) t2->addAnimation(new QPropertyAnimation(p5, "opacity")); t2->addAnimation(new QPropertyAnimation(p6, "opacity")); - QAbstractTransition *t3 = state3->addTransition(button, SIGNAL(clicked()), state1); + QAbstractTransition *t3 = state3->addTransition(button, &QAbstractButton::clicked, state1); t3->addAnimation(new QPropertyAnimation(box, "geometry")); t3->addAnimation(new QPropertyAnimation(widget, "geometry")); t3->addAnimation(new QPropertyAnimation(p1, "pos")); diff --git a/examples/widgets/animation/stickman/lifecycle.cpp b/examples/widgets/animation/stickman/lifecycle.cpp index dbe9a299b4..5d4c406b2e 100644 --- a/examples/widgets/animation/stickman/lifecycle.cpp +++ b/examples/widgets/animation/stickman/lifecycle.cpp @@ -61,11 +61,11 @@ class KeyPressTransition: public QSignalTransition { public: KeyPressTransition(GraphicsView *receiver, Qt::Key key) - : QSignalTransition(receiver, SIGNAL(keyPressed(int))), m_key(key) + : QSignalTransition(receiver, &GraphicsView::keyPressed), m_key(key) { } KeyPressTransition(GraphicsView *receiver, Qt::Key key, QAbstractState *target) - : QSignalTransition(receiver, SIGNAL(keyPressed(int))), m_key(key) + : QSignalTransition(receiver, &GraphicsView::keyPressed), m_key(key) { setTargetState(target); } @@ -132,8 +132,10 @@ LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) QTimer *timer = new QTimer(lightningBlink); timer->setSingleShot(true); timer->setInterval(100); - QObject::connect(lightningBlink, SIGNAL(entered()), timer, SLOT(start())); - QObject::connect(lightningBlink, SIGNAL(exited()), timer, SLOT(stop())); + QObject::connect(lightningBlink, &QAbstractState::entered, + timer, QOverload<>::of(&QTimer::start)); + QObject::connect(lightningBlink, &QAbstractState::exited, + timer, &QTimer::stop); //! [5] m_dead = new QState(m_machine); @@ -151,7 +153,7 @@ LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) // Lightning strikes at random m_alive->addTransition(new LightningStrikesTransition(lightningBlink)); //! [0] - lightningBlink->addTransition(timer, SIGNAL(timeout()), m_dead); + lightningBlink->addTransition(timer, &QTimer::timeout, m_dead); //! [0] m_machine->setInitialState(m_alive); @@ -206,14 +208,14 @@ QState *LifeCycle::makeState(QState *parentState, const QString &animationFileNa topLevel->setInitialState(frameState); else //! [2] - previousState->addTransition(previousState, SIGNAL(propertiesAssigned()), frameState); + previousState->addTransition(previousState, &QState::propertiesAssigned, frameState); //! [2] previousState = frameState; } // Loop - previousState->addTransition(previousState, SIGNAL(propertiesAssigned()), topLevel->initialState()); + previousState->addTransition(previousState, &QState::propertiesAssigned, topLevel->initialState()); return topLevel; diff --git a/examples/widgets/animation/stickman/stickman.cpp b/examples/widgets/animation/stickman/stickman.cpp index b7a2d87ada..8b183d87d5 100644 --- a/examples/widgets/animation/stickman/stickman.cpp +++ b/examples/widgets/animation/stickman/stickman.cpp @@ -126,7 +126,7 @@ StickMan::StickMan() // Set up start position of limbs for (int i=0; iaddTransition(leftMoveStop); //The animation is finished, it means we reached the border of the screen, the boat is stopped so we move to the stop state - moveStateLeft->addTransition(movementAnimation, SIGNAL(finished()), stopState); - moveStateRight->addTransition(movementAnimation, SIGNAL(finished()), stopState); + moveStateLeft->addTransition(movementAnimation, &QAbstractAnimation::finished, stopState); + moveStateRight->addTransition(movementAnimation, &QAbstractAnimation::finished, stopState); //We set up the keys for dropping bombs KeyLaunchTransition *upFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); @@ -187,13 +187,13 @@ Boat::Boat() : PixmapItem(QString("boat"), GraphicsScene::Big), destroyedState->setAnimation(destroyAnimation); //Play a nice animation when the boat is destroyed - moving->addTransition(this, SIGNAL(boatDestroyed()), destroyedState); + moving->addTransition(this, &Boat::boatDestroyed, destroyedState); //Transition to final state when the destroyed animation is finished - destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); + destroyedState->addTransition(destroyedState, &QAnimationState::animationFinished, final); //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()), this, SIGNAL(boatExecutionFinished())); + connect(machine,&QState::finished, this, &Boat::boatExecutionFinished); } diff --git a/examples/widgets/animation/sub-attaq/bomb.cpp b/examples/widgets/animation/sub-attaq/bomb.cpp index a80d2d46c5..76e4575293 100644 --- a/examples/widgets/animation/sub-attaq/bomb.cpp +++ b/examples/widgets/animation/sub-attaq/bomb.cpp @@ -83,8 +83,8 @@ void Bomb::launch(Bomb::Direction direction) anim->setEndValue(QPointF(x() + delta*2,scene()->height())); anim->setDuration(y()/2*60); launchAnimation->addAnimation(anim); - connect(anim,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant))); - connect(this, SIGNAL(bombExploded()), launchAnimation, SLOT(stop())); + connect(anim,&QVariantAnimation::valueChanged,this,&Bomb::onAnimationLaunchValueChanged); + connect(this, &Bomb::bombExploded, launchAnimation, &QAbstractAnimation::stop); //We setup the state machine of the bomb QStateMachine *machine = new QStateMachine(this); @@ -98,13 +98,13 @@ void Bomb::launch(Bomb::Direction direction) machine->setInitialState(launched); //### Add a nice animation when the bomb is destroyed - launched->addTransition(this, SIGNAL(bombExploded()),final); + launched->addTransition(this, &Bomb::bombExploded,final); //If the animation is finished, then we move to the final state - launched->addTransition(launched, SIGNAL(animationFinished()), final); + launched->addTransition(launched, &QAnimationState::animationFinished, final); //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(bombExecutionFinished())); + connect(machine,&QState::finished,this, &Bomb::bombExecutionFinished); machine->start(); diff --git a/examples/widgets/animation/sub-attaq/graphicsscene.cpp b/examples/widgets/animation/sub-attaq/graphicsscene.cpp index e0913f99f6..3205cdc54d 100644 --- a/examples/widgets/animation/sub-attaq/graphicsscene.cpp +++ b/examples/widgets/animation/sub-attaq/graphicsscene.cpp @@ -191,15 +191,15 @@ void GraphicsScene::setupScene(QAction *newAction, QAction *quitAction) lettersFadingState->setAnimation(lettersGroupFading); //if new game then we fade out the welcome screen and start playing - lettersMovingState->addTransition(newAction, SIGNAL(triggered()), lettersFadingState); - lettersFadingState->addTransition(lettersFadingState, SIGNAL(animationFinished()), gameState); + lettersMovingState->addTransition(newAction, &QAction::triggered, lettersFadingState); + lettersFadingState->addTransition(lettersFadingState, &QAnimationState::animationFinished, gameState); //New Game is triggered then player start playing - gameState->addTransition(newAction, SIGNAL(triggered()), gameState); + gameState->addTransition(newAction, &QAction::triggered, gameState); //Wanna quit, then connect to CTRL+Q - gameState->addTransition(quitAction, SIGNAL(triggered()), final); - lettersMovingState->addTransition(quitAction, SIGNAL(triggered()), final); + gameState->addTransition(quitAction, &QAction::triggered, final); + lettersMovingState->addTransition(quitAction, &QAction::triggered, final); //Welcome screen is the initial state machine->setInitialState(lettersMovingState); @@ -207,27 +207,27 @@ void GraphicsScene::setupScene(QAction *newAction, QAction *quitAction) machine->start(); //We reach the final state, then we quit - connect(machine, SIGNAL(finished()), qApp, SLOT(quit())); + connect(machine, &QStateMachine::finished, qApp, &QApplication::quit); } void GraphicsScene::addItem(Bomb *bomb) { bombs.insert(bomb); - connect(bomb,SIGNAL(bombExecutionFinished()),this, SLOT(onBombExecutionFinished())); + connect(bomb,&Bomb::bombExecutionFinished,this, &GraphicsScene::onBombExecutionFinished); QGraphicsScene::addItem(bomb); } void GraphicsScene::addItem(Torpedo *torpedo) { torpedos.insert(torpedo); - connect(torpedo,SIGNAL(torpedoExecutionFinished()),this, SLOT(onTorpedoExecutionFinished())); + connect(torpedo,&Torpedo::torpedoExecutionFinished,this, &GraphicsScene::onTorpedoExecutionFinished); QGraphicsScene::addItem(torpedo); } void GraphicsScene::addItem(SubMarine *submarine) { submarines.insert(submarine); - connect(submarine,SIGNAL(subMarineExecutionFinished()),this, SLOT(onSubMarineExecutionFinished())); + connect(submarine,&SubMarine::subMarineExecutionFinished,this, &GraphicsScene::onSubMarineExecutionFinished); QGraphicsScene::addItem(submarine); } diff --git a/examples/widgets/animation/sub-attaq/qanimationstate.cpp b/examples/widgets/animation/sub-attaq/qanimationstate.cpp index ae24af6da3..fc0da7cea2 100644 --- a/examples/widgets/animation/sub-attaq/qanimationstate.cpp +++ b/examples/widgets/animation/sub-attaq/qanimationstate.cpp @@ -73,7 +73,7 @@ QAnimationState *s = new QAnimationState(machine->rootState()); QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); s->setAnimation(animation); QState *s2 = new QState(machine->rootState()); -s->addTransition(s, SIGNAL(animationFinished()), s2); +s->addTransition(s, &QAnimationState::animationFinished, s2); machine.start(); \endcode @@ -107,13 +107,13 @@ void QAnimationState::setAnimation(QAbstractAnimation *animation) //Disconnect from the previous animation if exist if(m_animation) - disconnect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + disconnect(m_animation, &QAbstractAnimation::finished, this, &QAnimationState::animationFinished); m_animation = animation; if (m_animation) { //connect the new animation - connect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + connect(m_animation, &QAbstractAnimation::finished, this, &QAnimationState::animationFinished); } } diff --git a/examples/widgets/animation/sub-attaq/states.cpp b/examples/widgets/animation/sub-attaq/states.cpp index e19704db7b..8a3a97a20f 100644 --- a/examples/widgets/animation/sub-attaq/states.cpp +++ b/examples/widgets/animation/sub-attaq/states.cpp @@ -124,7 +124,7 @@ void PlayState::onEntry(QEvent *) WinState *winState = new WinState(scene, this, machine); //The boat has been destroyed then the game is finished - levelState->addTransition(scene->boat, SIGNAL(boatExecutionFinished()),lostState); + levelState->addTransition(scene->boat, &Boat::boatExecutionFinished,lostState); //This transition check if we won or not WinTransition *winTransition = new WinTransition(scene, this, winState); @@ -157,7 +157,7 @@ void PlayState::onEntry(QEvent *) winState->addTransition(spaceTransition); //We lost we should reach the final state - lostState->addTransition(lostState, SIGNAL(finished()), final); + lostState->addTransition(lostState, &QState::finished, final); machine->start(); } @@ -291,8 +291,8 @@ UpdateScoreState::UpdateScoreState(QState *parent) : QState(parent) /** Win transition */ UpdateScoreTransition::UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) - : QSignalTransition(scene,SIGNAL(subMarineDestroyed(int))), - game(game), scene(scene) + : QSignalTransition(scene, &GraphicsScene::subMarineDestroyed), + game(game), scene(scene) { setTargetState(target); } @@ -309,8 +309,8 @@ bool UpdateScoreTransition::eventTest(QEvent *event) /** Win transition */ WinTransition::WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) - : QSignalTransition(scene,SIGNAL(allSubMarineDestroyed(int))), - game(game), scene(scene) + : QSignalTransition(scene, &GraphicsScene::allSubMarineDestroyed), + game(game), scene(scene) { setTargetState(target); } diff --git a/examples/widgets/animation/sub-attaq/submarine.cpp b/examples/widgets/animation/sub-attaq/submarine.cpp index a451185ce0..775e75ceed 100644 --- a/examples/widgets/animation/sub-attaq/submarine.cpp +++ b/examples/widgets/animation/sub-attaq/submarine.cpp @@ -106,7 +106,7 @@ SubMarine::SubMarine(int type, const QString &name, int points) : PixmapItem(QSt //This is the initial state of the moving root state moving->setInitialState(movement); - movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); + movement->addTransition(this, &SubMarine::subMarineStateChanged, moving); //This is the initial state of the machine machine->setInitialState(moving); @@ -115,23 +115,23 @@ SubMarine::SubMarine(int type, const QString &name, int points) : PixmapItem(QSt QFinalState *final = new QFinalState(machine); //If the moving animation is finished we move to the return state - movement->addTransition(movement, SIGNAL(animationFinished()), rotation); + movement->addTransition(movement, &QAnimationState::animationFinished, rotation); //If the return animation is finished we move to the moving state - rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); + rotation->addTransition(rotation, &QAnimationState::animationFinished, movement); //This state play the destroyed animation QAnimationState *destroyedState = new QAnimationState(machine); destroyedState->setAnimation(setupDestroyAnimation(this)); //Play a nice animation when the submarine is destroyed - moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); + moving->addTransition(this, &SubMarine::subMarineDestroyed, destroyedState); //Transition to final state when the destroyed animation is finished - destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); + destroyedState->addTransition(destroyedState, &QAnimationState::animationFinished, final); //The machine has finished to be executed, then the submarine is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); + connect(machine,&QState::finished,this, &SubMarine::subMarineExecutionFinished); machine->start(); } diff --git a/examples/widgets/animation/sub-attaq/submarine_p.h b/examples/widgets/animation/sub-attaq/submarine_p.h index 698b4b494f..1c2cb7ceac 100644 --- a/examples/widgets/animation/sub-attaq/submarine_p.h +++ b/examples/widgets/animation/sub-attaq/submarine_p.h @@ -80,7 +80,8 @@ public: explicit MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) { movementAnimation = new QPropertyAnimation(submarine, "pos"); - connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &))); + connect(movementAnimation, &QPropertyAnimation::valueChanged, + this, &MovementState::onAnimationMovementValueChanged); setAnimation(movementAnimation); AnimationManager::self()->registerAnimation(movementAnimation); this->submarine = submarine; diff --git a/examples/widgets/animation/sub-attaq/torpedo.cpp b/examples/widgets/animation/sub-attaq/torpedo.cpp index 2e9d970326..5f8ef2f2b8 100644 --- a/examples/widgets/animation/sub-attaq/torpedo.cpp +++ b/examples/widgets/animation/sub-attaq/torpedo.cpp @@ -73,8 +73,8 @@ void Torpedo::launch() launchAnimation->setEndValue(QPointF(x(),qobject_cast(scene())->sealLevel() - 15)); launchAnimation->setEasingCurve(QEasingCurve::InQuad); launchAnimation->setDuration(y()/currentSpeed*10); - connect(launchAnimation,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant))); - connect(this,SIGNAL(torpedoExploded()), launchAnimation, SLOT(stop())); + connect(launchAnimation,&QVariantAnimation::valueChanged,this,&Torpedo::onAnimationLaunchValueChanged); + connect(this,&Torpedo::torpedoExploded, launchAnimation, &QAbstractAnimation::stop); //We setup the state machine of the torpedo QStateMachine *machine = new QStateMachine(this); @@ -89,13 +89,13 @@ void Torpedo::launch() machine->setInitialState(launched); //### Add a nice animation when the torpedo is destroyed - launched->addTransition(this, SIGNAL(torpedoExploded()),final); + launched->addTransition(this, &Torpedo::torpedoExploded,final); //If the animation is finished, then we move to the final state - launched->addTransition(launched, SIGNAL(animationFinished()), final); + launched->addTransition(launched, &QAnimationState::animationFinished, final); //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(torpedoExecutionFinished())); + connect(machine,&QState::finished,this, &Torpedo::torpedoExecutionFinished); machine->start(); } diff --git a/examples/widgets/effects/fademessage/fademessage.cpp b/examples/widgets/effects/fademessage/fademessage.cpp index 9943147bb7..4c3a70bb4f 100644 --- a/examples/widgets/effects/fademessage/fademessage.cpp +++ b/examples/widgets/effects/fademessage/fademessage.cpp @@ -131,7 +131,7 @@ void FadeMessage::setupScene() QPushButton *press = new QPushButton; press->setText(tr("Press me")); - connect(press, SIGNAL(clicked()), SLOT(togglePopup())); + connect(press, &QAbstractButton::clicked, this, &FadeMessage::togglePopup); m_scene.addWidget(press); press->move(300, 500); diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp index 1637c1f781..3c65206c02 100644 --- a/examples/widgets/graphicsview/boxes/scene.cpp +++ b/examples/widgets/graphicsview/boxes/scene.cpp @@ -111,7 +111,7 @@ ColorEdit::ColorEdit(QRgb initialColor, int id) m_button->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); layout->addWidget(m_button); - connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); + connect(m_lineEdit, &QLineEdit::editingFinished, this, &ColorEdit::editDone); } void ColorEdit::editDone() @@ -166,7 +166,7 @@ FloatEdit::FloatEdit(float initialValue, int id) m_lineEdit = new QLineEdit(QString::number(m_value)); layout->addWidget(m_lineEdit); - connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); + connect(m_lineEdit, &QLineEdit::editingFinished, this, &FloatEdit::editDone); } void FloatEdit::editDone() @@ -252,7 +252,7 @@ void TwoSidedGraphicsWidget::animateFlip() .translate(-r.width() / 2, -r.height() / 2)); if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180)) - QTimer::singleShot(25, this, SLOT(animateFlip())); + QTimer::singleShot(25, this, &TwoSidedGraphicsWidget::animateFlip); } QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) @@ -307,7 +307,7 @@ RenderOptionsDialog::RenderOptionsDialog() check->setCheckState(Qt::Unchecked); // Dynamic cube maps are only enabled when multi-texturing and render to texture are available. check->setEnabled(glActiveTexture && glGenFramebuffersEXT); - connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int))); + connect(check, &QCheckBox::stateChanged, this, &RenderOptionsDialog::dynamicCubemapToggled); layout->addWidget(check, 0, 0, 1, 2); ++row; @@ -356,7 +356,7 @@ RenderOptionsDialog::RenderOptionsDialog() ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1); m_parameterEdits << colorEdit; layout->addWidget(colorEdit); - connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int))); + connect(colorEdit, &ColorEdit::colorChanged, this, &RenderOptionsDialog::setColorParameter); ++row; } else if (type == "float") { layout->addWidget(new QLabel(m_parameterNames.back())); @@ -364,7 +364,7 @@ RenderOptionsDialog::RenderOptionsDialog() FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1); m_parameterEdits << floatEdit; layout->addWidget(floatEdit); - connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int))); + connect(floatEdit, &FloatEdit::valueChanged, this, &RenderOptionsDialog::setFloatParameter); ++row; } } @@ -375,13 +375,15 @@ RenderOptionsDialog::RenderOptionsDialog() layout->addWidget(new QLabel(tr("Texture:"))); m_textureCombo = new QComboBox; - connect(m_textureCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(textureChanged(int))); + connect(m_textureCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &RenderOptionsDialog::textureChanged); layout->addWidget(m_textureCombo); ++row; layout->addWidget(new QLabel(tr("Shader:"))); m_shaderCombo = new QComboBox; - connect(m_shaderCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(shaderChanged(int))); + connect(m_shaderCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &RenderOptionsDialog::shaderChanged); layout->addWidget(m_shaderCombo); ++row; @@ -439,15 +441,15 @@ ItemDialog::ItemDialog() button = new QPushButton(tr("Add Qt box")); layout->addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(triggerNewQtBox())); + connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewQtBox); button = new QPushButton(tr("Add circle")); layout->addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(triggerNewCircleItem())); + connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewCircleItem); button = new QPushButton(tr("Add square")); layout->addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(triggerNewSquareItem())); + connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewSquareItem); layout->addStretch(1); } @@ -506,21 +508,21 @@ Scene::Scene(int width, int height, int maxTextureSize) m_renderOptions->move(20, 120); m_renderOptions->resize(m_renderOptions->sizeHint()); - connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int))); - connect(m_renderOptions, SIGNAL(colorParameterChanged(QString,QRgb)), this, SLOT(setColorParameter(QString,QRgb))); - connect(m_renderOptions, SIGNAL(floatParameterChanged(QString,float)), this, SLOT(setFloatParameter(QString,float))); - connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int))); - connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int))); + connect(m_renderOptions, &RenderOptionsDialog::dynamicCubemapToggled, this, &Scene::toggleDynamicCubemap); + connect(m_renderOptions, &RenderOptionsDialog::colorParameterChanged, this, &Scene::setColorParameter); + connect(m_renderOptions, &RenderOptionsDialog::floatParameterChanged, this, &Scene::setFloatParameter); + connect(m_renderOptions, &RenderOptionsDialog::textureChanged, this, &Scene::setTexture); + connect(m_renderOptions, &RenderOptionsDialog::shaderChanged, this, &Scene::setShader); m_itemDialog = new ItemDialog; - connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType))); + connect(m_itemDialog, &ItemDialog::newItemTriggered, this, &Scene::newItem); TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this); twoSided->setWidget(0, m_renderOptions); twoSided->setWidget(1, m_itemDialog); - connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); - connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); + connect(m_renderOptions, &RenderOptionsDialog::doubleClicked, twoSided, &TwoSidedGraphicsWidget::flip); + connect(m_itemDialog, &ItemDialog::doubleClicked, twoSided, &TwoSidedGraphicsWidget::flip); addItem(new QtBox(64, width - 64, height - 64)); addItem(new QtBox(64, width - 64, 64)); @@ -531,7 +533,7 @@ Scene::Scene(int width, int height, int maxTextureSize) m_timer = new QTimer(this); m_timer->setInterval(20); - connect(m_timer, SIGNAL(timeout()), this, SLOT(update())); + connect(m_timer, &QTimer::timeout, this, [this](){ update(); }); m_timer->start(); m_time.start(); diff --git a/examples/widgets/graphicsview/chip/view.cpp b/examples/widgets/graphicsview/chip/view.cpp index 491f1a54cf..9676c13ff7 100644 --- a/examples/widgets/graphicsview/chip/view.cpp +++ b/examples/widgets/graphicsview/chip/view.cpp @@ -190,22 +190,22 @@ View::View(const QString &name, QWidget *parent) topLayout->addWidget(resetButton, 2, 1); setLayout(topLayout); - connect(resetButton, SIGNAL(clicked()), this, SLOT(resetView())); - connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); - connect(rotateSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); - connect(graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(setResetButtonEnabled())); - connect(graphicsView->horizontalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(setResetButtonEnabled())); - connect(selectModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); - connect(dragModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); - connect(antialiasButton, SIGNAL(toggled(bool)), this, SLOT(toggleAntialiasing())); - connect(openGlButton, SIGNAL(toggled(bool)), this, SLOT(toggleOpenGL())); - connect(rotateLeftIcon, SIGNAL(clicked()), this, SLOT(rotateLeft())); - connect(rotateRightIcon, SIGNAL(clicked()), this, SLOT(rotateRight())); - connect(zoomInIcon, SIGNAL(clicked()), this, SLOT(zoomIn())); - connect(zoomOutIcon, SIGNAL(clicked()), this, SLOT(zoomOut())); - connect(printButton, SIGNAL(clicked()), this, SLOT(print())); + connect(resetButton, &QAbstractButton::clicked, this, &View::resetView); + connect(zoomSlider, &QAbstractSlider::valueChanged, this, &View::setupMatrix); + connect(rotateSlider, &QAbstractSlider::valueChanged, this, &View::setupMatrix); + connect(graphicsView->verticalScrollBar(), &QAbstractSlider::valueChanged, + this, &View::setResetButtonEnabled); + connect(graphicsView->horizontalScrollBar(), &QAbstractSlider::valueChanged, + this, &View::setResetButtonEnabled); + connect(selectModeButton, &QAbstractButton::toggled, this, &View::togglePointerMode); + connect(dragModeButton, &QAbstractButton::toggled, this, &View::togglePointerMode); + connect(antialiasButton, &QAbstractButton::toggled, this, &View::toggleAntialiasing); + connect(openGlButton, &QAbstractButton::toggled, this, &View::toggleOpenGL); + connect(rotateLeftIcon, &QAbstractButton::clicked, this, &View::rotateLeft); + connect(rotateRightIcon, &QAbstractButton::clicked, this, &View::rotateRight); + connect(zoomInIcon, &QAbstractButton::clicked, this, &View::zoomIn); + connect(zoomOutIcon, &QAbstractButton::clicked, this, &View::zoomOut); + connect(printButton, &QAbstractButton::clicked, this, &View::print); setupMatrix(); } diff --git a/examples/widgets/graphicsview/collidingmice/main.cpp b/examples/widgets/graphicsview/collidingmice/main.cpp index 91aee70b86..dfb20815b9 100644 --- a/examples/widgets/graphicsview/collidingmice/main.cpp +++ b/examples/widgets/graphicsview/collidingmice/main.cpp @@ -92,7 +92,7 @@ int main(int argc, char **argv) view.show(); QTimer timer; - QObject::connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance())); + QObject::connect(&timer, &QTimer::timeout, &scene, &QGraphicsScene::advance); timer.start(1000 / 33); return app.exec(); diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.cpp b/examples/widgets/graphicsview/diagramscene/diagramscene.cpp index bbbc512b55..51d855cc75 100644 --- a/examples/widgets/graphicsview/diagramscene/diagramscene.cpp +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.cpp @@ -169,10 +169,10 @@ void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) textItem->setFont(myFont); textItem->setTextInteractionFlags(Qt::TextEditorInteraction); textItem->setZValue(1000.0); - connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)), - this, SLOT(editorLostFocus(DiagramTextItem*))); - connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)), - this, SIGNAL(itemSelected(QGraphicsItem*))); + connect(textItem, &DiagramTextItem::lostFocus, + this, &DiagramScene::editorLostFocus); + connect(textItem, &DiagramTextItem::selectedChange, + this, &DiagramScene::itemSelected); addItem(textItem); textItem->setDefaultTextColor(myTextColor); textItem->setPos(mouseEvent->scenePos()); diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp index 36353674ea..875c41b284 100644 --- a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp +++ b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp @@ -67,12 +67,12 @@ MainWindow::MainWindow() scene = new DiagramScene(itemMenu, this); scene->setSceneRect(QRectF(0, 0, 5000, 5000)); - connect(scene, SIGNAL(itemInserted(DiagramItem*)), - this, SLOT(itemInserted(DiagramItem*))); - connect(scene, SIGNAL(textInserted(QGraphicsTextItem*)), - this, SLOT(textInserted(QGraphicsTextItem*))); - connect(scene, SIGNAL(itemSelected(QGraphicsItem*)), - this, SLOT(itemSelected(QGraphicsItem*))); + connect(scene, &DiagramScene::itemInserted, + this, &MainWindow::itemInserted); + connect(scene, &DiagramScene::textInserted, + this, &MainWindow::textInserted); + connect(scene, &DiagramScene::itemSelected, + this, &MainWindow::itemSelected); createToolbars(); QHBoxLayout *layout = new QHBoxLayout; @@ -332,8 +332,8 @@ void MainWindow::createToolBox() { buttonGroup = new QButtonGroup(this); buttonGroup->setExclusive(false); - connect(buttonGroup, SIGNAL(buttonClicked(int)), - this, SLOT(buttonGroupClicked(int))); + connect(buttonGroup, QOverload::of(&QButtonGroup::buttonClicked), + this, &MainWindow::buttonGroupClicked); QGridLayout *layout = new QGridLayout; layout->addWidget(createCellWidget(tr("Conditional"), DiagramItem::Conditional), 0, 0); layout->addWidget(createCellWidget(tr("Process"), DiagramItem::Step),0, 1); @@ -359,8 +359,8 @@ void MainWindow::createToolBox() itemWidget->setLayout(layout); backgroundButtonGroup = new QButtonGroup(this); - connect(backgroundButtonGroup, SIGNAL(buttonClicked(QAbstractButton*)), - this, SLOT(backgroundButtonGroupClicked(QAbstractButton*))); + connect(backgroundButtonGroup, QOverload::of(&QButtonGroup::buttonClicked), + this, &MainWindow::backgroundButtonGroupClicked); QGridLayout *backgroundLayout = new QGridLayout; backgroundLayout->addWidget(createBackgroundCellWidget(tr("Blue Grid"), @@ -395,44 +395,44 @@ void MainWindow::createActions() tr("Bring to &Front"), this); toFrontAction->setShortcut(tr("Ctrl+F")); toFrontAction->setStatusTip(tr("Bring item to front")); - connect(toFrontAction, SIGNAL(triggered()), this, SLOT(bringToFront())); + connect(toFrontAction, &QAction::triggered, this, &MainWindow::bringToFront); //! [23] sendBackAction = new QAction(QIcon(":/images/sendtoback.png"), tr("Send to &Back"), this); sendBackAction->setShortcut(tr("Ctrl+T")); sendBackAction->setStatusTip(tr("Send item to back")); - connect(sendBackAction, SIGNAL(triggered()), this, SLOT(sendToBack())); + connect(sendBackAction, &QAction::triggered, this, &MainWindow::sendToBack); deleteAction = new QAction(QIcon(":/images/delete.png"), tr("&Delete"), this); deleteAction->setShortcut(tr("Delete")); deleteAction->setStatusTip(tr("Delete item from diagram")); - connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteItem())); + connect(deleteAction, &QAction::triggered, this, &MainWindow::deleteItem); exitAction = new QAction(tr("E&xit"), this); exitAction->setShortcuts(QKeySequence::Quit); exitAction->setStatusTip(tr("Quit Scenediagram example")); - connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); + connect(exitAction, &QAction::triggered, this, &QWidget::close); boldAction = new QAction(tr("Bold"), this); boldAction->setCheckable(true); QPixmap pixmap(":/images/bold.png"); boldAction->setIcon(QIcon(pixmap)); boldAction->setShortcut(tr("Ctrl+B")); - connect(boldAction, SIGNAL(triggered()), this, SLOT(handleFontChange())); + connect(boldAction, &QAction::triggered, this, &MainWindow::handleFontChange); italicAction = new QAction(QIcon(":/images/italic.png"), tr("Italic"), this); italicAction->setCheckable(true); italicAction->setShortcut(tr("Ctrl+I")); - connect(italicAction, SIGNAL(triggered()), this, SLOT(handleFontChange())); + connect(italicAction, &QAction::triggered, this, &MainWindow::handleFontChange); underlineAction = new QAction(QIcon(":/images/underline.png"), tr("Underline"), this); underlineAction->setCheckable(true); underlineAction->setShortcut(tr("Ctrl+U")); - connect(underlineAction, SIGNAL(triggered()), this, SLOT(handleFontChange())); + connect(underlineAction, &QAction::triggered, this, &MainWindow::handleFontChange); aboutAction = new QAction(tr("A&bout"), this); aboutAction->setShortcut(tr("F1")); - connect(aboutAction, SIGNAL(triggered()), this, SLOT(about())); + connect(aboutAction, &QAction::triggered, this, &MainWindow::about); } //! [24] @@ -462,8 +462,8 @@ void MainWindow::createToolbars() editToolBar->addAction(sendBackAction); fontCombo = new QFontComboBox(); - connect(fontCombo, SIGNAL(currentFontChanged(QFont)), - this, SLOT(currentFontChanged(QFont))); + connect(fontCombo, &QFontComboBox::currentFontChanged, + this, &MainWindow::currentFontChanged); fontSizeCombo = new QComboBox; fontSizeCombo->setEditable(true); @@ -471,8 +471,8 @@ void MainWindow::createToolbars() fontSizeCombo->addItem(QString().setNum(i)); QIntValidator *validator = new QIntValidator(2, 64, this); fontSizeCombo->setValidator(validator); - connect(fontSizeCombo, SIGNAL(currentIndexChanged(QString)), - this, SLOT(fontSizeChanged(QString))); + connect(fontSizeCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &MainWindow::fontSizeChanged); fontColorToolButton = new QToolButton; fontColorToolButton->setPopupMode(QToolButton::MenuButtonPopup); @@ -480,8 +480,8 @@ void MainWindow::createToolbars() textAction = fontColorToolButton->menu()->defaultAction(); fontColorToolButton->setIcon(createColorToolButtonIcon(":/images/textpointer.png", Qt::black)); fontColorToolButton->setAutoFillBackground(true); - connect(fontColorToolButton, SIGNAL(clicked()), - this, SLOT(textButtonTriggered())); + connect(fontColorToolButton, &QAbstractButton::clicked, + this, &MainWindow::textButtonTriggered); //! [26] fillColorToolButton = new QToolButton; @@ -490,8 +490,8 @@ void MainWindow::createToolbars() fillAction = fillColorToolButton->menu()->defaultAction(); fillColorToolButton->setIcon(createColorToolButtonIcon( ":/images/floodfill.png", Qt::white)); - connect(fillColorToolButton, SIGNAL(clicked()), - this, SLOT(fillButtonTriggered())); + connect(fillColorToolButton, &QAbstractButton::clicked, + this, &MainWindow::fillButtonTriggered); //! [26] lineColorToolButton = new QToolButton; @@ -500,8 +500,8 @@ void MainWindow::createToolbars() lineAction = lineColorToolButton->menu()->defaultAction(); lineColorToolButton->setIcon(createColorToolButtonIcon( ":/images/linecolor.png", Qt::black)); - connect(lineColorToolButton, SIGNAL(clicked()), - this, SLOT(lineButtonTriggered())); + connect(lineColorToolButton, &QAbstractButton::clicked, + this, &MainWindow::lineButtonTriggered); textToolBar = addToolBar(tr("Font")); textToolBar->addWidget(fontCombo); @@ -526,16 +526,16 @@ void MainWindow::createToolbars() pointerTypeGroup = new QButtonGroup(this); pointerTypeGroup->addButton(pointerButton, int(DiagramScene::MoveItem)); pointerTypeGroup->addButton(linePointerButton, int(DiagramScene::InsertLine)); - connect(pointerTypeGroup, SIGNAL(buttonClicked(int)), - this, SLOT(pointerGroupClicked(int))); + connect(pointerTypeGroup, QOverload::of(&QButtonGroup::buttonClicked), + this, &MainWindow::pointerGroupClicked); sceneScaleCombo = new QComboBox; QStringList scales; scales << tr("50%") << tr("75%") << tr("100%") << tr("125%") << tr("150%"); sceneScaleCombo->addItems(scales); sceneScaleCombo->setCurrentIndex(2); - connect(sceneScaleCombo, SIGNAL(currentIndexChanged(QString)), - this, SLOT(sceneScaleChanged(QString))); + connect(sceneScaleCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &MainWindow::sceneScaleChanged); pointerToolbar = addToolBar(tr("Pointer type")); pointerToolbar->addWidget(pointerButton); diff --git a/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp b/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp index 158c31d9c1..c181a03e85 100644 --- a/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp +++ b/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp @@ -58,10 +58,10 @@ CustomProxy::CustomProxy(QGraphicsItem *parent, Qt::WindowFlags wFlags) : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(0) { timeLine = new QTimeLine(250, this); - connect(timeLine, SIGNAL(valueChanged(qreal)), - this, SLOT(updateStep(qreal))); - connect(timeLine, SIGNAL(stateChanged(QTimeLine::State)), - this, SLOT(stateChanged(QTimeLine::State))); + connect(timeLine, &QTimeLine::valueChanged, + this, &CustomProxy::updateStep); + connect(timeLine, &QTimeLine::stateChanged, + this, &CustomProxy::stateChanged); } QRectF CustomProxy::boundingRect() const -- cgit v1.2.3 From 1f2c23a7ca1699b345578aeb52fbd97b612e079a Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 12:00:48 +0100 Subject: Cleanup Widgets examples - foreach Cleanup the Widget examples - replace foreach with range-based for loop in subdirectory tools, touch and tutorials Change-Id: I008d23b5993a18a3332fe9f5e5bca68cb0561066 Reviewed-by: Luca Beldi Reviewed-by: Sze Howe Koh Reviewed-by: Paul Wicking --- examples/widgets/tools/codecs/mainwindow.cpp | 14 ++++----- examples/widgets/tools/codecs/previewform.cpp | 2 +- .../tools/echoplugin/echowindow/echowindow.cpp | 3 +- examples/widgets/tools/i18n/languagechooser.cpp | 8 ++--- .../widgets/tools/settingseditor/settingstree.cpp | 6 ++-- examples/widgets/touch/dials/main.cpp | 4 +-- examples/widgets/touch/fingerpaint/mainwindow.cpp | 6 ++-- .../widgets/touch/fingerpaint/scribblearea.cpp | 6 ++-- examples/widgets/touch/pinchzoom/mouse.cpp | 2 +- .../tutorials/widgets/nestedlayouts/main.cpp | 35 +++++++++++----------- 10 files changed, 45 insertions(+), 41 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/tools/codecs/mainwindow.cpp b/examples/widgets/tools/codecs/mainwindow.cpp index 229c2ccfd4..53db9fe61f 100644 --- a/examples/widgets/tools/codecs/mainwindow.cpp +++ b/examples/widgets/tools/codecs/mainwindow.cpp @@ -127,11 +127,10 @@ void MainWindow::about() void MainWindow::aboutToShowSaveAsMenu() { - QString currentText = textEdit->toPlainText(); - - foreach (QAction *action, saveAsActs) { - QByteArray codecName = action->data().toByteArray(); - QTextCodec *codec = QTextCodec::codecForName(codecName); + const QString currentText = textEdit->toPlainText(); + for (QAction *action : qAsConst(saveAsActs)) { + const QByteArray codecName = action->data().toByteArray(); + const QTextCodec *codec = QTextCodec::codecForName(codecName); action->setVisible(codec && codec->canEncode(currentText)); } } @@ -142,7 +141,8 @@ void MainWindow::findCodecs() QRegularExpression iso8859RegExp("^ISO[- ]8859-([0-9]+).*$"); QRegularExpressionMatch match; - foreach (int mib, QTextCodec::availableMibs()) { + const QList mibs = QTextCodec::availableMibs(); + for (int mib : mibs) { QTextCodec *codec = QTextCodec::codecForMib(mib); QString sortKey = codec->name().toUpper(); @@ -177,7 +177,7 @@ void MainWindow::createMenus() QMenu *saveAsMenu = fileMenu->addMenu(tr("&Save As")); connect(saveAsMenu, &QMenu::aboutToShow, this, &MainWindow::aboutToShowSaveAsMenu); - foreach (const QTextCodec *codec, codecs) { + for (const QTextCodec *codec : qAsConst(codecs)) { const QByteArray name = codec->name(); QAction *action = saveAsMenu->addAction(tr("%1...").arg(QLatin1String(name))); action->setData(QVariant(name)); diff --git a/examples/widgets/tools/codecs/previewform.cpp b/examples/widgets/tools/codecs/previewform.cpp index d19b9c0833..206b5757cd 100644 --- a/examples/widgets/tools/codecs/previewform.cpp +++ b/examples/widgets/tools/codecs/previewform.cpp @@ -182,7 +182,7 @@ PreviewForm::PreviewForm(QWidget *parent) void PreviewForm::setCodecList(const QList &list) { encodingComboBox->clear(); - foreach (const QTextCodec *codec, list) { + for (const QTextCodec *codec : list) { encodingComboBox->addItem(QLatin1String(codec->name()), QVariant(codec->mibEnum())); } diff --git a/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp b/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp index 64b59d506e..6886a4cd88 100644 --- a/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp +++ b/examples/widgets/tools/echoplugin/echowindow/echowindow.cpp @@ -113,7 +113,8 @@ bool EchoWindow::loadPlugin() } #endif pluginsDir.cd("plugins"); - foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { + const QStringList entries = pluginsDir.entryList(QDir::Files); + for (const QString &fileName : entries) { QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = pluginLoader.instance(); if (plugin) { diff --git a/examples/widgets/tools/i18n/languagechooser.cpp b/examples/widgets/tools/i18n/languagechooser.cpp index 58cf9d4047..f07d0ddee3 100644 --- a/examples/widgets/tools/i18n/languagechooser.cpp +++ b/examples/widgets/tools/i18n/languagechooser.cpp @@ -148,14 +148,14 @@ void LanguageChooser::checkBoxToggled() void LanguageChooser::showAll() { - foreach (QCheckBox *checkBox, qmFileForCheckBoxMap.keys()) - checkBox->setChecked(true); + for (auto it = qmFileForCheckBoxMap.keyBegin(); it != qmFileForCheckBoxMap.keyEnd(); ++it) + (*it)->setChecked(true); } void LanguageChooser::hideAll() { - foreach (QCheckBox *checkBox, qmFileForCheckBoxMap.keys()) - checkBox->setChecked(false); + for (auto it = qmFileForCheckBoxMap.keyBegin(); it != qmFileForCheckBoxMap.keyEnd(); ++it) + (*it)->setChecked(false); } QStringList LanguageChooser::findQmFiles() diff --git a/examples/widgets/tools/settingseditor/settingstree.cpp b/examples/widgets/tools/settingseditor/settingstree.cpp index 4ca843784e..8585792787 100644 --- a/examples/widgets/tools/settingseditor/settingstree.cpp +++ b/examples/widgets/tools/settingseditor/settingstree.cpp @@ -170,7 +170,8 @@ void SettingsTree::updateChildItems(QTreeWidgetItem *parent) { int dividerIndex = 0; - foreach (QString group, settings->childGroups()) { + const QStringList childGroups = settings->childGroups(); + for (const QString &group : childGroups) { QTreeWidgetItem *child; int childIndex = findChild(parent, group, dividerIndex); if (childIndex != -1) { @@ -190,7 +191,8 @@ void SettingsTree::updateChildItems(QTreeWidgetItem *parent) settings->endGroup(); } - foreach (const QString &key, settings->childKeys()) { + const QStringList childKeys = settings->childKeys(); + for (const QString &key : childKeys) { QTreeWidgetItem *child; int childIndex = findChild(parent, key, 0); diff --git a/examples/widgets/touch/dials/main.cpp b/examples/widgets/touch/dials/main.cpp index 071f485de3..059dfdc716 100644 --- a/examples/widgets/touch/dials/main.cpp +++ b/examples/widgets/touch/dials/main.cpp @@ -60,8 +60,8 @@ int main(int argc, char **argv) QWidget window; Ui::Dials dialsUi; dialsUi.setupUi(&window); - QList sliders = window.findChildren(); - foreach (QAbstractSlider *slider, sliders) + const QList sliders = window.findChildren(); + for (QAbstractSlider *slider : sliders) slider->setAttribute(Qt::WA_AcceptTouchEvents); window.showMaximized(); return app.exec(); diff --git a/examples/widgets/touch/fingerpaint/mainwindow.cpp b/examples/widgets/touch/fingerpaint/mainwindow.cpp index b0d91d25bf..2f7ec38d1a 100644 --- a/examples/widgets/touch/fingerpaint/mainwindow.cpp +++ b/examples/widgets/touch/fingerpaint/mainwindow.cpp @@ -129,7 +129,8 @@ void MainWindow::createActions() openAct->setShortcut(tr("Ctrl+O")); connect(openAct, &QAction::triggered, this, &MainWindow::open); - foreach (QByteArray format, QImageWriter::supportedImageFormats()) { + const QList imageFormats = QImageWriter::supportedImageFormats(); + for (const QByteArray &format : imageFormats) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); @@ -163,8 +164,7 @@ void MainWindow::createMenus() //! [15] //! [16] { saveAsMenu = new QMenu(tr("&Save As"), this); - foreach (QAction *action, saveAsActs) - saveAsMenu->addAction(action); + saveAsMenu->addActions(saveAsActs); fileMenu = new QMenu(tr("&File"), this); fileMenu->addAction(openAct); diff --git a/examples/widgets/touch/fingerpaint/scribblearea.cpp b/examples/widgets/touch/fingerpaint/scribblearea.cpp index aa4e60c934..0b0c4476d9 100644 --- a/examples/widgets/touch/fingerpaint/scribblearea.cpp +++ b/examples/widgets/touch/fingerpaint/scribblearea.cpp @@ -195,9 +195,9 @@ bool ScribbleArea::event(QEvent *event) case QEvent::TouchUpdate: case QEvent::TouchEnd: { - QTouchEvent *touch = static_cast(event); - QList touchPoints = static_cast(event)->touchPoints(); - foreach (const QTouchEvent::TouchPoint &touchPoint, touchPoints) { + const QTouchEvent *touch = static_cast(event); + const QList touchPoints = static_cast(event)->touchPoints(); + for (const QTouchEvent::TouchPoint &touchPoint : touchPoints) { switch (touchPoint.state()) { case Qt::TouchPointStationary: case Qt::TouchPointReleased: diff --git a/examples/widgets/touch/pinchzoom/mouse.cpp b/examples/widgets/touch/pinchzoom/mouse.cpp index 1e6814be13..1dfd7d749c 100644 --- a/examples/widgets/touch/pinchzoom/mouse.cpp +++ b/examples/widgets/touch/pinchzoom/mouse.cpp @@ -163,7 +163,7 @@ void Mouse::timerEvent(QTimerEvent *) << mapToScene(0, 0) << mapToScene(-30, -50) << mapToScene(30, -50)); - foreach (QGraphicsItem *item, dangerMice) { + for (QGraphicsItem *item : dangerMice) { if (item == this) continue; diff --git a/examples/widgets/tutorials/widgets/nestedlayouts/main.cpp b/examples/widgets/tutorials/widgets/nestedlayouts/main.cpp index 9acc74b469..8880dbe3d0 100644 --- a/examples/widgets/tutorials/widgets/nestedlayouts/main.cpp +++ b/examples/widgets/tutorials/widgets/nestedlayouts/main.cpp @@ -76,25 +76,26 @@ int main(int argc, char *argv[]) //! [set up the model] QStandardItemModel model; - model.setHorizontalHeaderLabels( - QStringList() << QApplication::translate("nestedlayouts", "Name") - << QApplication::translate("nestedlayouts", "Office")); + model.setHorizontalHeaderLabels({ QApplication::translate("nestedlayouts", "Name"), + QApplication::translate("nestedlayouts", "Office") }); - QList rows = QList() - << (QStringList() << "Verne Nilsen" << "123") - << (QStringList() << "Carlos Tang" << "77") - << (QStringList() << "Bronwyn Hawcroft" << "119") - << (QStringList() << "Alessandro Hanssen" << "32") - << (QStringList() << "Andrew John Bakken" << "54") - << (QStringList() << "Vanessa Weatherley" << "85") - << (QStringList() << "Rebecca Dickens" << "17") - << (QStringList() << "David Bradley" << "42") - << (QStringList() << "Knut Walters" << "25") - << (QStringList() << "Andrea Jones" << "34"); + const QStringList rows[] = { + QStringList{ QStringLiteral("Verne Nilsen"), QStringLiteral("123") }, + QStringList{ QStringLiteral("Carlos Tang"), QStringLiteral("77") }, + QStringList{ QStringLiteral("Bronwyn Hawcroft"), QStringLiteral("119") }, + QStringList{ QStringLiteral("Alessandro Hanssen"), QStringLiteral("32") }, + QStringList{ QStringLiteral("Andrew John Bakken"), QStringLiteral("54") }, + QStringList{ QStringLiteral("Vanessa Weatherley"), QStringLiteral("85") }, + QStringList{ QStringLiteral("Rebecca Dickens"), QStringLiteral("17") }, + QStringList{ QStringLiteral("David Bradley"), QStringLiteral("42") }, + QStringList{ QStringLiteral("Knut Walters"), QStringLiteral("25") }, + QStringList{ QStringLiteral("Andrea Jones"), QStringLiteral("34") } + }; - foreach (QStringList row, rows) { - QList items; - foreach (QString text, row) + QList items; + for (const QStringList &row : rows) { + items.clear(); + for (const QString &text : row) items.append(new QStandardItem(text)); model.appendRow(items); } -- cgit v1.2.3 From c590aa678d5c27162b0ca7191fa76b1d3a112767 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 23 Nov 2018 20:05:42 +0100 Subject: Cleanup SimpleTreeModel example Cleanup the SimpleTreeModel example: - include own headers first - use nullptr - add sanity checks Change-Id: If57d608e3919368b2022ff86aede8de9c2ba7369 Reviewed-by: Luca Beldi Reviewed-by: Sze Howe Koh --- examples/widgets/doc/src/simpletreemodel.qdoc | 5 ++-- .../widgets/itemviews/simpletreemodel/treeitem.cpp | 18 +++++------ .../widgets/itemviews/simpletreemodel/treeitem.h | 8 ++--- .../itemviews/simpletreemodel/treemodel.cpp | 35 ++++++++++------------ .../widgets/itemviews/simpletreemodel/treemodel.h | 2 +- 5 files changed, 31 insertions(+), 37 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/doc/src/simpletreemodel.qdoc b/examples/widgets/doc/src/simpletreemodel.qdoc index a50197b04d..f5fe93897c 100644 --- a/examples/widgets/doc/src/simpletreemodel.qdoc +++ b/examples/widgets/doc/src/simpletreemodel.qdoc @@ -170,9 +170,8 @@ \snippet itemviews/simpletreemodel/treeitem.cpp 5 - Column data is returned by the \c data() function, taking advantage of - QList's ability to provide sensible default values if the column number - is out of range: + Column data is returned by the \c data() function. The bounds are checked + before accessing the container with the data: \snippet itemviews/simpletreemodel/treeitem.cpp 6 diff --git a/examples/widgets/itemviews/simpletreemodel/treeitem.cpp b/examples/widgets/itemviews/simpletreemodel/treeitem.cpp index e11639ff67..41fe24e737 100644 --- a/examples/widgets/itemviews/simpletreemodel/treeitem.cpp +++ b/examples/widgets/itemviews/simpletreemodel/treeitem.cpp @@ -54,16 +54,12 @@ A container for items of data supplied by the simple tree model. */ -#include - #include "treeitem.h" //! [0] -TreeItem::TreeItem(const QList &data, TreeItem *parent) -{ - m_parentItem = parent; - m_itemData = data; -} +TreeItem::TreeItem(const QVector &data, TreeItem *parent) + : m_itemData(data), m_parentItem(parent) +{} //! [0] //! [1] @@ -83,7 +79,9 @@ void TreeItem::appendChild(TreeItem *item) //! [3] TreeItem *TreeItem::child(int row) { - return m_childItems.value(row); + if (row < 0 || row >= m_childItems.size()) + return nullptr; + return m_childItems.at(row); } //! [3] @@ -104,7 +102,9 @@ int TreeItem::columnCount() const //! [6] QVariant TreeItem::data(int column) const { - return m_itemData.value(column); + if (column < 0 || column >= m_itemData.size()) + return QVariant(); + return m_itemData.at(column); } //! [6] diff --git a/examples/widgets/itemviews/simpletreemodel/treeitem.h b/examples/widgets/itemviews/simpletreemodel/treeitem.h index 8d0bb49627..390433597d 100644 --- a/examples/widgets/itemviews/simpletreemodel/treeitem.h +++ b/examples/widgets/itemviews/simpletreemodel/treeitem.h @@ -51,14 +51,14 @@ #ifndef TREEITEM_H #define TREEITEM_H -#include #include +#include //! [0] class TreeItem { public: - explicit TreeItem(const QList &data, TreeItem *parentItem = 0); + explicit TreeItem(const QVector &data, TreeItem *parentItem = nullptr); ~TreeItem(); void appendChild(TreeItem *child); @@ -71,8 +71,8 @@ public: TreeItem *parentItem(); private: - QList m_childItems; - QList m_itemData; + QVector m_childItems; + QVector m_itemData; TreeItem *m_parentItem; }; //! [0] diff --git a/examples/widgets/itemviews/simpletreemodel/treemodel.cpp b/examples/widgets/itemviews/simpletreemodel/treemodel.cpp index 1de970d398..cfa65846ed 100644 --- a/examples/widgets/itemviews/simpletreemodel/treemodel.cpp +++ b/examples/widgets/itemviews/simpletreemodel/treemodel.cpp @@ -55,8 +55,8 @@ models. */ -#include "treeitem.h" #include "treemodel.h" +#include "treeitem.h" #include @@ -64,10 +64,8 @@ TreeModel::TreeModel(const QString &data, QObject *parent) : QAbstractItemModel(parent) { - QList rootData; - rootData << "Title" << "Summary"; - rootItem = new TreeItem(rootData); - setupModelData(data.split(QString("\n")), rootItem); + rootItem = new TreeItem({tr("Title"), tr("Summary")}); + setupModelData(data.split('\n'), rootItem); } //! [0] @@ -83,8 +81,7 @@ int TreeModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return static_cast(parent.internalPointer())->columnCount(); - else - return rootItem->columnCount(); + return rootItem->columnCount(); } //! [2] @@ -107,7 +104,7 @@ QVariant TreeModel::data(const QModelIndex &index, int role) const Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const { if (!index.isValid()) - return 0; + return Qt::NoItemFlags; return QAbstractItemModel::flags(index); } @@ -125,8 +122,7 @@ QVariant TreeModel::headerData(int section, Qt::Orientation orientation, //! [5] //! [6] -QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) - const +QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); @@ -141,8 +137,7 @@ QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) TreeItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); - else - return QModelIndex(); + return QModelIndex(); } //! [6] @@ -180,8 +175,8 @@ int TreeModel::rowCount(const QModelIndex &parent) const void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) { - QList parents; - QList indentations; + QVector parents; + QVector indentations; parents << parent; indentations << 0; @@ -195,14 +190,15 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) position++; } - QString lineData = lines[number].mid(position).trimmed(); + const QString lineData = lines[number].mid(position).trimmed(); if (!lineData.isEmpty()) { // Read the column data from the rest of the line. - QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); - QList columnData; - for (int column = 0; column < columnStrings.count(); ++column) - columnData << columnStrings[column]; + const QStringList columnStrings = lineData.split('\t', QString::SkipEmptyParts); + QVector columnData; + columnData.reserve(columnStrings.count()); + for (const QString &columnString : columnStrings) + columnData << columnString; if (position > indentations.last()) { // The last child of the current parent is now the new parent @@ -222,7 +218,6 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) // Append a new item to the current parent's list of children. parents.last()->appendChild(new TreeItem(columnData, parents.last())); } - ++number; } } diff --git a/examples/widgets/itemviews/simpletreemodel/treemodel.h b/examples/widgets/itemviews/simpletreemodel/treemodel.h index 800728fb82..76fd03f112 100644 --- a/examples/widgets/itemviews/simpletreemodel/treemodel.h +++ b/examples/widgets/itemviews/simpletreemodel/treemodel.h @@ -63,7 +63,7 @@ class TreeModel : public QAbstractItemModel Q_OBJECT public: - explicit TreeModel(const QString &data, QObject *parent = 0); + explicit TreeModel(const QString &data, QObject *parent = nullptr); ~TreeModel(); QVariant data(const QModelIndex &index, int role) const override; -- cgit v1.2.3 From aa32510430d6a5e58cb456faeb072d9f189872fe Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 2 Dec 2018 14:11:13 +0100 Subject: Cleanup Widgets examples - nullptr Cleanup the widgets examples - replace 0 with nullptr Change-Id: Id4bf119b9a41f6d10117f3a613a6e604128fa196 Reviewed-by: Konstantin Shegunov Reviewed-by: Edward Welbourne Reviewed-by: Paul Wicking --- examples/widgets/animation/animatedtiles/main.cpp | 2 +- examples/widgets/animation/easing/window.h | 2 +- examples/widgets/animation/moveblocks/main.cpp | 3 ++- examples/widgets/animation/stickman/graphicsview.cpp | 4 +++- examples/widgets/animation/stickman/graphicsview.h | 2 +- examples/widgets/animation/stickman/lifecycle.cpp | 7 +++---- examples/widgets/animation/stickman/stickman.cpp | 3 +-- .../widgets/animation/sub-attaq/animationmanager.cpp | 2 +- examples/widgets/animation/sub-attaq/boat.cpp | 5 +++-- examples/widgets/animation/sub-attaq/boat_p.h | 19 ++++++++++++------- examples/widgets/animation/sub-attaq/mainwindow.cpp | 3 ++- examples/widgets/animation/sub-attaq/mainwindow.h | 2 +- examples/widgets/animation/sub-attaq/pixmapitem.cpp | 3 ++- examples/widgets/animation/sub-attaq/pixmapitem.h | 2 +- .../widgets/animation/sub-attaq/qanimationstate.cpp | 2 +- examples/widgets/animation/sub-attaq/states.cpp | 7 ++----- examples/widgets/desktop/systray/main.cpp | 2 +- examples/widgets/desktop/systray/window.cpp | 2 +- examples/widgets/dialogs/classwizard/classwizard.cpp | 4 ++-- examples/widgets/dialogs/findfiles/window.cpp | 4 ++-- examples/widgets/dialogs/standarddialogs/dialog.cpp | 4 ++-- .../graphicsview/embeddeddialogs/customproxy.cpp | 4 ++-- .../widgets/graphicsview/embeddeddialogs/main.cpp | 2 +- .../widgets/layouts/borderlayout/borderlayout.cpp | 9 +++------ examples/widgets/layouts/flowlayout/flowlayout.cpp | 5 ++--- .../widgets/mainwindows/mainwindow/colorswatch.cpp | 8 ++++---- examples/widgets/mainwindows/mainwindow/toolbar.cpp | 6 +++--- examples/widgets/mainwindows/mdi/mainwindow.cpp | 6 +++--- examples/widgets/mainwindows/sdi/mainwindow.cpp | 2 +- examples/widgets/widgets/analogclock/analogclock.h | 2 +- examples/widgets/widgets/calculator/button.h | 2 +- examples/widgets/widgets/calculator/calculator.h | 2 +- .../widgets/widgets/charactermap/characterwidget.h | 2 +- examples/widgets/widgets/charactermap/mainwindow.cpp | 2 +- examples/widgets/widgets/codeeditor/codeeditor.h | 2 +- examples/widgets/widgets/digitalclock/digitalclock.h | 2 +- examples/widgets/widgets/elidedlabel/elidedlabel.h | 2 +- examples/widgets/widgets/elidedlabel/testwidget.h | 2 +- examples/widgets/widgets/groupbox/window.h | 2 +- examples/widgets/widgets/lineedits/window.cpp | 2 +- examples/widgets/widgets/movie/movieplayer.h | 2 +- examples/widgets/widgets/scribble/scribblearea.h | 2 +- examples/widgets/widgets/shapedclock/shapedclock.h | 2 +- examples/widgets/widgets/sliders/slidersgroup.h | 2 +- examples/widgets/widgets/styles/widgetgallery.h | 2 +- .../widgets/widgets/stylesheet/stylesheeteditor.h | 2 +- examples/widgets/widgets/tablet/tabletapplication.h | 5 ++--- examples/widgets/widgets/tetrix/tetrixboard.h | 2 +- examples/widgets/widgets/tooltips/sortingbox.cpp | 4 ++-- examples/widgets/widgets/validators/ledwidget.h | 2 +- examples/widgets/widgets/validators/localeselector.h | 2 +- examples/widgets/widgets/wiggly/dialog.h | 2 +- examples/widgets/widgets/wiggly/wigglywidget.h | 2 +- examples/widgets/widgets/windowflags/previewwindow.h | 2 +- 54 files changed, 91 insertions(+), 90 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/animation/animatedtiles/main.cpp b/examples/widgets/animation/animatedtiles/main.cpp index 8edd64e482..553b620e41 100644 --- a/examples/widgets/animation/animatedtiles/main.cpp +++ b/examples/widgets/animation/animatedtiles/main.cpp @@ -69,7 +69,7 @@ class Button : public QGraphicsWidget { Q_OBJECT public: - Button(const QPixmap &pixmap, QGraphicsItem *parent = 0) + Button(const QPixmap &pixmap, QGraphicsItem *parent = nullptr) : QGraphicsWidget(parent), _pix(pixmap) { setAcceptHoverEvents(true); diff --git a/examples/widgets/animation/easing/window.h b/examples/widgets/animation/easing/window.h index 2b7b2a5bf3..541377a981 100644 --- a/examples/widgets/animation/easing/window.h +++ b/examples/widgets/animation/easing/window.h @@ -66,7 +66,7 @@ public: class Window : public QWidget { Q_OBJECT public: - Window(QWidget *parent = 0); + Window(QWidget *parent = nullptr); private slots: void curveChanged(int row); void pathChanged(int index); diff --git a/examples/widgets/animation/moveblocks/main.cpp b/examples/widgets/animation/moveblocks/main.cpp index e59b17cbf9..d03b57cd5e 100644 --- a/examples/widgets/animation/moveblocks/main.cpp +++ b/examples/widgets/animation/moveblocks/main.cpp @@ -169,7 +169,8 @@ class GraphicsView : public QGraphicsView { Q_OBJECT public: - GraphicsView(QGraphicsScene *scene, QWidget *parent = NULL) : QGraphicsView(scene, parent) + GraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr) + : QGraphicsView(scene, parent) { } diff --git a/examples/widgets/animation/stickman/graphicsview.cpp b/examples/widgets/animation/stickman/graphicsview.cpp index 9cb57fcd9e..7058e15345 100644 --- a/examples/widgets/animation/stickman/graphicsview.cpp +++ b/examples/widgets/animation/stickman/graphicsview.cpp @@ -55,7 +55,9 @@ #include #include -GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent), m_editor(0) {} +GraphicsView::GraphicsView(QWidget *parent) + : QGraphicsView(parent), m_editor(nullptr) +{} void GraphicsView::keyPressEvent(QKeyEvent *e) { diff --git a/examples/widgets/animation/stickman/graphicsview.h b/examples/widgets/animation/stickman/graphicsview.h index 56396bb780..361fee219d 100644 --- a/examples/widgets/animation/stickman/graphicsview.h +++ b/examples/widgets/animation/stickman/graphicsview.h @@ -58,7 +58,7 @@ class GraphicsView: public QGraphicsView { Q_OBJECT public: - GraphicsView(QWidget *parent = 0); + GraphicsView(QWidget *parent = nullptr); protected: void resizeEvent(QResizeEvent *event) override; diff --git a/examples/widgets/animation/stickman/lifecycle.cpp b/examples/widgets/animation/stickman/lifecycle.cpp index 5d4c406b2e..046e3f4cd1 100644 --- a/examples/widgets/animation/stickman/lifecycle.cpp +++ b/examples/widgets/animation/stickman/lifecycle.cpp @@ -175,9 +175,8 @@ void LifeCycle::addActivity(const QString &fileName, Qt::Key key, QObject *sende QState *state = makeState(m_alive, fileName); m_alive->addTransition(new KeyPressTransition(m_keyReceiver, key, state)); - if((sender != NULL) || (signal != NULL)) { + if (sender || signal) m_alive->addTransition(sender, signal, state); - } } QState *LifeCycle::makeState(QState *parentState, const QString &animationFileName) @@ -192,7 +191,7 @@ QState *LifeCycle::makeState(QState *parentState, const QString &animationFileNa } const int frameCount = animation.totalFrames(); - QState *previousState = 0; + QState *previousState = nullptr; for (int i=0; isetObjectName(QString::fromLatin1("frame %0").arg(i)); - if (previousState == 0) + if (previousState == nullptr) topLevel->setInitialState(frameState); else //! [2] diff --git a/examples/widgets/animation/stickman/stickman.cpp b/examples/widgets/animation/stickman/stickman.cpp index 8b183d87d5..5725f64eec 100644 --- a/examples/widgets/animation/stickman/stickman.cpp +++ b/examples/widgets/animation/stickman/stickman.cpp @@ -176,8 +176,7 @@ Node *StickMan::node(int idx) const { if (idx >= 0 && idx < NodeCount) return m_nodes[idx]; - else - return 0; + return nullptr; } void StickMan::timerEvent(QTimerEvent *) diff --git a/examples/widgets/animation/sub-attaq/animationmanager.cpp b/examples/widgets/animation/sub-attaq/animationmanager.cpp index 62dac7852a..e3dc27f37f 100644 --- a/examples/widgets/animation/sub-attaq/animationmanager.cpp +++ b/examples/widgets/animation/sub-attaq/animationmanager.cpp @@ -56,7 +56,7 @@ #include // the universe's only animation manager -AnimationManager *AnimationManager::instance = 0; +AnimationManager *AnimationManager::instance = nullptr; AnimationManager::AnimationManager() { diff --git a/examples/widgets/animation/sub-attaq/boat.cpp b/examples/widgets/animation/sub-attaq/boat.cpp index 9f4feba2ec..9037d54878 100644 --- a/examples/widgets/animation/sub-attaq/boat.cpp +++ b/examples/widgets/animation/sub-attaq/boat.cpp @@ -92,8 +92,9 @@ static QAbstractAnimation *setupDestroyAnimation(Boat *boat) -Boat::Boat() : PixmapItem(QString("boat"), GraphicsScene::Big), - speed(0), bombsAlreadyLaunched(0), direction(Boat::None), movementAnimation(0) +Boat::Boat() + : PixmapItem(QString("boat"), GraphicsScene::Big), + speed(0), bombsAlreadyLaunched(0), direction(Boat::None) { setZValue(4); setFlags(QGraphicsItem::ItemIsFocusable); diff --git a/examples/widgets/animation/sub-attaq/boat_p.h b/examples/widgets/animation/sub-attaq/boat_p.h index de11ff9555..8ebfeb27f5 100644 --- a/examples/widgets/animation/sub-attaq/boat_p.h +++ b/examples/widgets/animation/sub-attaq/boat_p.h @@ -146,7 +146,8 @@ private: class MoveStateRight : public QState { public: - explicit MoveStateRight(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + explicit MoveStateRight(Boat *boat, QState *parent = nullptr) + : QState(parent), boat(boat) { } protected: @@ -163,7 +164,8 @@ private: class MoveStateLeft : public QState { public: - explicit MoveStateLeft(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + explicit MoveStateLeft(Boat *boat, QState *parent = nullptr) + : QState(parent), boat(boat) { } protected: @@ -180,7 +182,8 @@ private: class StopState : public QState { public: - explicit StopState(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + explicit StopState(Boat *boat, QState *parent = nullptr) + : QState(parent), boat(boat) { } protected: @@ -198,13 +201,14 @@ private: class LaunchStateRight : public QState { public: - explicit LaunchStateRight(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + explicit LaunchStateRight(Boat *boat, QState *parent = nullptr) + : QState(parent), boat(boat) { } protected: void onEntry(QEvent *) override { - Bomb *b = new Bomb(); + Bomb *b = new Bomb; b->setPos(boat->x()+boat->size().width(),boat->y()); GraphicsScene *scene = static_cast(boat->scene()); scene->addItem(b); @@ -219,13 +223,14 @@ private: class LaunchStateLeft : public QState { public: - explicit LaunchStateLeft(Boat *boat,QState *parent = 0) : QState(parent), boat(boat) + explicit LaunchStateLeft(Boat *boat, QState *parent = nullptr) + : QState(parent), boat(boat) { } protected: void onEntry(QEvent *) override { - Bomb *b = new Bomb(); + Bomb *b = new Bomb; b->setPos(boat->x() - b->size().width(), boat->y()); GraphicsScene *scene = static_cast(boat->scene()); scene->addItem(b); diff --git a/examples/widgets/animation/sub-attaq/mainwindow.cpp b/examples/widgets/animation/sub-attaq/mainwindow.cpp index b08a7d9f98..a4bb15b383 100644 --- a/examples/widgets/animation/sub-attaq/mainwindow.cpp +++ b/examples/widgets/animation/sub-attaq/mainwindow.cpp @@ -63,7 +63,8 @@ # include #endif -MainWindow::MainWindow() : QMainWindow(0) +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) { QMenu *file = menuBar()->addMenu(tr("&File")); diff --git a/examples/widgets/animation/sub-attaq/mainwindow.h b/examples/widgets/animation/sub-attaq/mainwindow.h index 8d3cc85cd1..c4fb9d324d 100644 --- a/examples/widgets/animation/sub-attaq/mainwindow.h +++ b/examples/widgets/animation/sub-attaq/mainwindow.h @@ -62,7 +62,7 @@ class MainWindow : public QMainWindow { Q_OBJECT public: - MainWindow(); + MainWindow(QWidget *parent = nullptr); private: GraphicsScene *scene; diff --git a/examples/widgets/animation/sub-attaq/pixmapitem.cpp b/examples/widgets/animation/sub-attaq/pixmapitem.cpp index 0723cdfb5d..9475d5c3f8 100644 --- a/examples/widgets/animation/sub-attaq/pixmapitem.cpp +++ b/examples/widgets/animation/sub-attaq/pixmapitem.cpp @@ -54,7 +54,8 @@ //Qt #include -PixmapItem::PixmapItem(const QString &fileName,GraphicsScene::Mode mode, QGraphicsItem * parent) : QGraphicsObject(parent) +PixmapItem::PixmapItem(const QString &fileName,GraphicsScene::Mode mode, QGraphicsItem * parent) + : QGraphicsObject(parent) { if (mode == GraphicsScene::Big) pix = QPixmap(QStringLiteral(":/big/") + fileName); diff --git a/examples/widgets/animation/sub-attaq/pixmapitem.h b/examples/widgets/animation/sub-attaq/pixmapitem.h index de8ed67a38..ec5c01857f 100644 --- a/examples/widgets/animation/sub-attaq/pixmapitem.h +++ b/examples/widgets/animation/sub-attaq/pixmapitem.h @@ -60,7 +60,7 @@ class PixmapItem : public QGraphicsObject { public: - PixmapItem(const QString &fileName, GraphicsScene::Mode mode, QGraphicsItem * parent = 0); + PixmapItem(const QString &fileName, GraphicsScene::Mode mode, QGraphicsItem *parent = nullptr); PixmapItem(const QString &fileName, QGraphicsScene *scene); QSizeF size() const; QRectF boundingRect() const override; diff --git a/examples/widgets/animation/sub-attaq/qanimationstate.cpp b/examples/widgets/animation/sub-attaq/qanimationstate.cpp index fc0da7cea2..ef88df8abe 100644 --- a/examples/widgets/animation/sub-attaq/qanimationstate.cpp +++ b/examples/widgets/animation/sub-attaq/qanimationstate.cpp @@ -84,7 +84,7 @@ machine.start(); Constructs a new state with the given \a parent state. */ QAnimationState::QAnimationState(QState *parent) - : QState(parent), m_animation(0) + : QState(parent), m_animation(nullptr) { } diff --git a/examples/widgets/animation/sub-attaq/states.cpp b/examples/widgets/animation/sub-attaq/states.cpp index 8a3a97a20f..cda10ccdaf 100644 --- a/examples/widgets/animation/sub-attaq/states.cpp +++ b/examples/widgets/animation/sub-attaq/states.cpp @@ -67,11 +67,8 @@ #include PlayState::PlayState(GraphicsScene *scene, QState *parent) - : QState(parent), - scene(scene), - machine(0), - currentLevel(0), - score(0) + : QState(parent), scene(scene), machine(nullptr), + currentLevel(0), score(0) { } diff --git a/examples/widgets/desktop/systray/main.cpp b/examples/widgets/desktop/systray/main.cpp index 49b0e10412..4e3e628767 100644 --- a/examples/widgets/desktop/systray/main.cpp +++ b/examples/widgets/desktop/systray/main.cpp @@ -62,7 +62,7 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); if (!QSystemTrayIcon::isSystemTrayAvailable()) { - QMessageBox::critical(0, QObject::tr("Systray"), + QMessageBox::critical(nullptr, QObject::tr("Systray"), QObject::tr("I couldn't detect any system tray " "on this system.")); return 1; diff --git a/examples/widgets/desktop/systray/window.cpp b/examples/widgets/desktop/systray/window.cpp index 05944c92a7..31fcd84821 100644 --- a/examples/widgets/desktop/systray/window.cpp +++ b/examples/widgets/desktop/systray/window.cpp @@ -176,7 +176,7 @@ void Window::showMessage() //! [6] void Window::messageClicked() { - QMessageBox::information(0, tr("Systray"), + QMessageBox::information(nullptr, tr("Systray"), tr("Sorry, I already gave what help I could.\n" "Maybe you should try asking a human?")); } diff --git a/examples/widgets/dialogs/classwizard/classwizard.cpp b/examples/widgets/dialogs/classwizard/classwizard.cpp index 3eab2f5fb2..81adf85b0d 100644 --- a/examples/widgets/dialogs/classwizard/classwizard.cpp +++ b/examples/widgets/dialogs/classwizard/classwizard.cpp @@ -139,7 +139,7 @@ void ClassWizard::accept() QFile headerFile(outputDir + '/' + header); if (!headerFile.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(0, QObject::tr("Simple Wizard"), + QMessageBox::warning(nullptr, QObject::tr("Simple Wizard"), QObject::tr("Cannot write file %1:\n%2") .arg(headerFile.fileName()) .arg(headerFile.errorString())); @@ -195,7 +195,7 @@ void ClassWizard::accept() QFile implementationFile(outputDir + '/' + implementation); if (!implementationFile.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(0, QObject::tr("Simple Wizard"), + QMessageBox::warning(nullptr, QObject::tr("Simple Wizard"), QObject::tr("Cannot write file %1:\n%2") .arg(implementationFile.fileName()) .arg(implementationFile.errorString())); diff --git a/examples/widgets/dialogs/findfiles/window.cpp b/examples/widgets/dialogs/findfiles/window.cpp index 1b16cdcd35..e1f7ccdcc4 100644 --- a/examples/widgets/dialogs/findfiles/window.cpp +++ b/examples/widgets/dialogs/findfiles/window.cpp @@ -182,7 +182,7 @@ QStringList Window::findFiles(const QStringList &files, const QString &text) for (int i = 0; i < files.size(); ++i) { progressDialog.setValue(i); - progressDialog.setLabelText(tr("Searching file number %1 of %n...", 0, files.size()).arg(i)); + progressDialog.setLabelText(tr("Searching file number %1 of %n...", nullptr, files.size()).arg(i)); QCoreApplication::processEvents(); //! [6] @@ -237,7 +237,7 @@ void Window::showFiles(const QStringList &paths) filesTable->setItem(row, 0, fileNameItem); filesTable->setItem(row, 1, sizeItem); } - filesFoundLabel->setText(tr("%n file(s) found (Double click on a file to open it)", 0, paths.size())); + filesFoundLabel->setText(tr("%n file(s) found (Double click on a file to open it)", nullptr, paths.size())); filesFoundLabel->setWordWrap(true); } //! [8] diff --git a/examples/widgets/dialogs/standarddialogs/dialog.cpp b/examples/widgets/dialogs/standarddialogs/dialog.cpp index 74a4131b38..4b59aab887 100644 --- a/examples/widgets/dialogs/standarddialogs/dialog.cpp +++ b/examples/widgets/dialogs/standarddialogs/dialog.cpp @@ -65,7 +65,7 @@ class DialogOptionsWidget : public QGroupBox { public: - explicit DialogOptionsWidget(QWidget *parent = 0); + explicit DialogOptionsWidget(QWidget *parent = nullptr); void addCheckBox(const QString &text, int value); void addSpacer(); @@ -492,7 +492,7 @@ void Dialog::questionMessage() void Dialog::warningMessage() { QMessageBox msgBox(QMessageBox::Warning, tr("QMessageBox::warning()"), - MESSAGE, 0, this); + MESSAGE, nullptr, this); msgBox.setDetailedText(MESSAGE_DETAILS); msgBox.addButton(tr("Save &Again"), QMessageBox::AcceptRole); msgBox.addButton(tr("&Continue"), QMessageBox::RejectRole); diff --git a/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp b/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp index c181a03e85..f510ebc07f 100644 --- a/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp +++ b/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp @@ -55,7 +55,7 @@ #include CustomProxy::CustomProxy(QGraphicsItem *parent, Qt::WindowFlags wFlags) - : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(0) + : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(nullptr) { timeLine = new QTimeLine(250, this); connect(timeLine, &QTimeLine::valueChanged, @@ -133,7 +133,7 @@ QVariant CustomProxy::itemChange(GraphicsItemChange change, const QVariant &valu currentPopup->installSceneEventFilter(this); } else if (scene()) { currentPopup->removeSceneEventFilter(this); - currentPopup = 0; + currentPopup = nullptr; } } else if (currentPopup && change == ItemSceneHasChanged) { currentPopup->installSceneEventFilter(this); diff --git a/examples/widgets/graphicsview/embeddeddialogs/main.cpp b/examples/widgets/graphicsview/embeddeddialogs/main.cpp index cbd5dd5890..501405e3ff 100644 --- a/examples/widgets/graphicsview/embeddeddialogs/main.cpp +++ b/examples/widgets/graphicsview/embeddeddialogs/main.cpp @@ -66,7 +66,7 @@ int main(int argc, char *argv[]) for (int y = 0; y < gridSize; ++y) { for (int x = 0; x < gridSize; ++x) { - CustomProxy *proxy = new CustomProxy(0, Qt::Window); + CustomProxy *proxy = new CustomProxy(nullptr, Qt::Window); proxy->setWidget(new EmbeddedDialog); QRectF rect = proxy->boundingRect(); diff --git a/examples/widgets/layouts/borderlayout/borderlayout.cpp b/examples/widgets/layouts/borderlayout/borderlayout.cpp index 9b142584c9..c929d3b2a4 100644 --- a/examples/widgets/layouts/borderlayout/borderlayout.cpp +++ b/examples/widgets/layouts/borderlayout/borderlayout.cpp @@ -98,10 +98,7 @@ int BorderLayout::count() const QLayoutItem *BorderLayout::itemAt(int index) const { ItemWrapper *wrapper = list.value(index); - if (wrapper) - return wrapper->item; - else - return 0; + return wrapper ? wrapper->item : nullptr; } QSize BorderLayout::minimumSize() const @@ -111,7 +108,7 @@ QSize BorderLayout::minimumSize() const void BorderLayout::setGeometry(const QRect &rect) { - ItemWrapper *center = 0; + ItemWrapper *center = nullptr; int eastWidth = 0; int westWidth = 0; int northHeight = 0; @@ -189,7 +186,7 @@ QLayoutItem *BorderLayout::takeAt(int index) ItemWrapper *layoutStruct = list.takeAt(index); return layoutStruct->item; } - return 0; + return nullptr; } void BorderLayout::add(QLayoutItem *item, Position position) diff --git a/examples/widgets/layouts/flowlayout/flowlayout.cpp b/examples/widgets/layouts/flowlayout/flowlayout.cpp index 9203da0ba1..b7064d98b1 100644 --- a/examples/widgets/layouts/flowlayout/flowlayout.cpp +++ b/examples/widgets/layouts/flowlayout/flowlayout.cpp @@ -116,8 +116,7 @@ QLayoutItem *FlowLayout::takeAt(int index) { if (index >= 0 && index < itemList.size()) return itemList.takeAt(index); - else - return 0; + return nullptr; } //! [5] @@ -215,7 +214,7 @@ int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const return -1; } else if (parent->isWidgetType()) { QWidget *pw = static_cast(parent); - return pw->style()->pixelMetric(pm, 0, pw); + return pw->style()->pixelMetric(pm, nullptr, pw); } else { return static_cast(parent)->spacing(); } diff --git a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp index 720f9a2085..240a04c897 100644 --- a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp +++ b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp @@ -584,7 +584,7 @@ void ColorSwatch::changeVerticalTitleBar(bool on) QSize BlueTitleBar::minimumSizeHint() const { QDockWidget *dw = qobject_cast(parentWidget()); - Q_ASSERT(dw != 0); + Q_ASSERT(dw); QSize result(leftPm.width() + rightPm.width(), centerPm.height()); if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) result.transpose(); @@ -605,7 +605,7 @@ void BlueTitleBar::paintEvent(QPaintEvent*) QRect rect = this->rect(); QDockWidget *dw = qobject_cast(parentWidget()); - Q_ASSERT(dw != 0); + Q_ASSERT(dw); if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { QSize s = rect.size(); @@ -632,7 +632,7 @@ void BlueTitleBar::mouseReleaseEvent(QMouseEvent *event) QRect rect = this->rect(); QDockWidget *dw = qobject_cast(parentWidget()); - Q_ASSERT(dw != 0); + Q_ASSERT(dw); if (dw->features() & QDockWidget::DockWidgetVerticalTitleBar) { QPoint p = pos; @@ -676,7 +676,7 @@ void BlueTitleBar::mouseReleaseEvent(QMouseEvent *event) void BlueTitleBar::updateMask() { QDockWidget *dw = qobject_cast(parent()); - Q_ASSERT(dw != 0); + Q_ASSERT(dw); QRect rect = dw->rect(); QPixmap bitmap(dw->size()); diff --git a/examples/widgets/mainwindows/mainwindow/toolbar.cpp b/examples/widgets/mainwindows/mainwindow/toolbar.cpp index 7c96f5b1be..096d3df5a8 100644 --- a/examples/widgets/mainwindows/mainwindow/toolbar.cpp +++ b/examples/widgets/mainwindows/mainwindow/toolbar.cpp @@ -208,7 +208,7 @@ ToolBar::ToolBar(const QString &title, QWidget *parent) void ToolBar::updateMenu() { QMainWindow *mainWindow = qobject_cast(parentWidget()); - Q_ASSERT(mainWindow != 0); + Q_ASSERT(mainWindow); const Qt::ToolBarArea area = mainWindow->toolBarArea(this); const Qt::ToolBarAreas areas = allowedAreas(); @@ -313,7 +313,7 @@ void ToolBar::place(Qt::ToolBarArea area, bool p) return; QMainWindow *mainWindow = qobject_cast(parentWidget()); - Q_ASSERT(mainWindow != 0); + Q_ASSERT(mainWindow); mainWindow->addToolBar(area, this); @@ -355,7 +355,7 @@ void ToolBar::placeBottom(bool p) void ToolBar::insertToolBarBreak() { QMainWindow *mainWindow = qobject_cast(parentWidget()); - Q_ASSERT(mainWindow != 0); + Q_ASSERT(mainWindow); mainWindow->insertToolBarBreak(this); } diff --git a/examples/widgets/mainwindows/mdi/mainwindow.cpp b/examples/widgets/mainwindows/mdi/mainwindow.cpp index 188de1893e..1e87c5a747 100644 --- a/examples/widgets/mainwindows/mdi/mainwindow.cpp +++ b/examples/widgets/mainwindows/mdi/mainwindow.cpp @@ -242,7 +242,7 @@ void MainWindow::about() void MainWindow::updateMenus() { - bool hasMdiChild = (activeMdiChild() != 0); + bool hasMdiChild = (activeMdiChild() != nullptr); saveAct->setEnabled(hasMdiChild); saveAsAct->setEnabled(hasMdiChild); #ifndef QT_NO_CLIPBOARD @@ -483,7 +483,7 @@ MdiChild *MainWindow::activeMdiChild() const { if (QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow()) return qobject_cast(activeSubWindow->widget()); - return 0; + return nullptr; } QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName) const @@ -495,7 +495,7 @@ QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName) const if (mdiChild->currentFile() == canonicalFilePath) return window; } - return 0; + return nullptr; } void MainWindow::switchLayoutDirection() diff --git a/examples/widgets/mainwindows/sdi/mainwindow.cpp b/examples/widgets/mainwindows/sdi/mainwindow.cpp index d44f7c918d..f3e3af8a1b 100644 --- a/examples/widgets/mainwindows/sdi/mainwindow.cpp +++ b/examples/widgets/mainwindows/sdi/mainwindow.cpp @@ -478,5 +478,5 @@ MainWindow *MainWindow::findMainWindow(const QString &fileName) const return mainWin; } - return 0; + return nullptr; } diff --git a/examples/widgets/widgets/analogclock/analogclock.h b/examples/widgets/widgets/analogclock/analogclock.h index 19e580d1ac..e2486a915f 100644 --- a/examples/widgets/widgets/analogclock/analogclock.h +++ b/examples/widgets/widgets/analogclock/analogclock.h @@ -59,7 +59,7 @@ class AnalogClock : public QWidget Q_OBJECT public: - AnalogClock(QWidget *parent = 0); + AnalogClock(QWidget *parent = nullptr); protected: void paintEvent(QPaintEvent *event) override; diff --git a/examples/widgets/widgets/calculator/button.h b/examples/widgets/widgets/calculator/button.h index 057640700f..7c6f26867f 100644 --- a/examples/widgets/widgets/calculator/button.h +++ b/examples/widgets/widgets/calculator/button.h @@ -59,7 +59,7 @@ class Button : public QToolButton Q_OBJECT public: - explicit Button(const QString &text, QWidget *parent = 0); + explicit Button(const QString &text, QWidget *parent = nullptr); QSize sizeHint() const override; }; diff --git a/examples/widgets/widgets/calculator/calculator.h b/examples/widgets/widgets/calculator/calculator.h index 6d7e336347..937de185e7 100644 --- a/examples/widgets/widgets/calculator/calculator.h +++ b/examples/widgets/widgets/calculator/calculator.h @@ -64,7 +64,7 @@ class Calculator : public QWidget Q_OBJECT public: - Calculator(QWidget *parent = 0); + Calculator(QWidget *parent = nullptr); private slots: void digitClicked(); diff --git a/examples/widgets/widgets/charactermap/characterwidget.h b/examples/widgets/widgets/charactermap/characterwidget.h index 53add51e6f..34e061e96b 100644 --- a/examples/widgets/widgets/charactermap/characterwidget.h +++ b/examples/widgets/widgets/charactermap/characterwidget.h @@ -68,7 +68,7 @@ class CharacterWidget : public QWidget Q_OBJECT public: - CharacterWidget(QWidget *parent = 0); + CharacterWidget(QWidget *parent = nullptr); QSize sizeHint() const override; public slots: diff --git a/examples/widgets/widgets/charactermap/mainwindow.cpp b/examples/widgets/widgets/charactermap/mainwindow.cpp index 76bd8f7799..1b6f77bf30 100644 --- a/examples/widgets/widgets/charactermap/mainwindow.cpp +++ b/examples/widgets/widgets/charactermap/mainwindow.cpp @@ -188,7 +188,7 @@ void MainWindow::filterChanged(int f) const QFontComboBox::FontFilter filter = filterCombo->itemData(f).value(); fontCombo->setFontFilters(filter); - statusBar()->showMessage(tr("%n font(s) found", 0, fontCombo->count())); + statusBar()->showMessage(tr("%n font(s) found", nullptr, fontCombo->count())); } void MainWindow::findSizes(const QFont &font) diff --git a/examples/widgets/widgets/codeeditor/codeeditor.h b/examples/widgets/widgets/codeeditor/codeeditor.h index 65be76d81d..fcfc188cf2 100644 --- a/examples/widgets/widgets/codeeditor/codeeditor.h +++ b/examples/widgets/widgets/codeeditor/codeeditor.h @@ -70,7 +70,7 @@ class CodeEditor : public QPlainTextEdit Q_OBJECT public: - CodeEditor(QWidget *parent = 0); + CodeEditor(QWidget *parent = nullptr); void lineNumberAreaPaintEvent(QPaintEvent *event); int lineNumberAreaWidth(); diff --git a/examples/widgets/widgets/digitalclock/digitalclock.h b/examples/widgets/widgets/digitalclock/digitalclock.h index 4365b965bf..31c12f39ab 100644 --- a/examples/widgets/widgets/digitalclock/digitalclock.h +++ b/examples/widgets/widgets/digitalclock/digitalclock.h @@ -59,7 +59,7 @@ class DigitalClock : public QLCDNumber Q_OBJECT public: - DigitalClock(QWidget *parent = 0); + DigitalClock(QWidget *parent = nullptr); private slots: void showTime(); diff --git a/examples/widgets/widgets/elidedlabel/elidedlabel.h b/examples/widgets/widgets/elidedlabel/elidedlabel.h index 8a2a40f49a..9d4fe5fef3 100644 --- a/examples/widgets/widgets/elidedlabel/elidedlabel.h +++ b/examples/widgets/widgets/elidedlabel/elidedlabel.h @@ -65,7 +65,7 @@ class ElidedLabel : public QFrame Q_PROPERTY(bool isElided READ isElided) public: - explicit ElidedLabel(const QString &text, QWidget *parent = 0); + explicit ElidedLabel(const QString &text, QWidget *parent = nullptr); void setText(const QString &text); const QString & text() const { return content; } diff --git a/examples/widgets/widgets/elidedlabel/testwidget.h b/examples/widgets/widgets/elidedlabel/testwidget.h index 840bc98b40..cd309d2316 100644 --- a/examples/widgets/widgets/elidedlabel/testwidget.h +++ b/examples/widgets/widgets/elidedlabel/testwidget.h @@ -64,7 +64,7 @@ class TestWidget : public QWidget Q_OBJECT public: - TestWidget(QWidget *parent = 0); + TestWidget(QWidget *parent = nullptr); protected: void resizeEvent(QResizeEvent *event) override; diff --git a/examples/widgets/widgets/groupbox/window.h b/examples/widgets/widgets/groupbox/window.h index 566fafa151..1f041fd003 100644 --- a/examples/widgets/widgets/groupbox/window.h +++ b/examples/widgets/widgets/groupbox/window.h @@ -63,7 +63,7 @@ class Window : public QWidget Q_OBJECT public: - Window(QWidget *parent = 0); + Window(QWidget *parent = nullptr); private: QGroupBox *createFirstExclusiveGroup(); diff --git a/examples/widgets/widgets/lineedits/window.cpp b/examples/widgets/widgets/lineedits/window.cpp index 47324589b7..0926f6f20b 100644 --- a/examples/widgets/widgets/lineedits/window.cpp +++ b/examples/widgets/widgets/lineedits/window.cpp @@ -206,7 +206,7 @@ void Window::validatorChanged(int index) { switch (index) { case 0: - validatorLineEdit->setValidator(0); + validatorLineEdit->setValidator(nullptr); break; case 1: validatorLineEdit->setValidator(new QIntValidator( diff --git a/examples/widgets/widgets/movie/movieplayer.h b/examples/widgets/widgets/movie/movieplayer.h index 9fa9604025..7d143bd37c 100644 --- a/examples/widgets/widgets/movie/movieplayer.h +++ b/examples/widgets/widgets/movie/movieplayer.h @@ -70,7 +70,7 @@ class MoviePlayer : public QWidget Q_OBJECT public: - MoviePlayer(QWidget *parent = 0); + MoviePlayer(QWidget *parent = nullptr); void openFile(const QString &fileName); private slots: diff --git a/examples/widgets/widgets/scribble/scribblearea.h b/examples/widgets/widgets/scribble/scribblearea.h index 7729fb5b89..100c45e133 100644 --- a/examples/widgets/widgets/scribble/scribblearea.h +++ b/examples/widgets/widgets/scribble/scribblearea.h @@ -62,7 +62,7 @@ class ScribbleArea : public QWidget Q_OBJECT public: - ScribbleArea(QWidget *parent = 0); + ScribbleArea(QWidget *parent = nullptr); bool openImage(const QString &fileName); bool saveImage(const QString &fileName, const char *fileFormat); diff --git a/examples/widgets/widgets/shapedclock/shapedclock.h b/examples/widgets/widgets/shapedclock/shapedclock.h index 6468d21618..a854d956b3 100644 --- a/examples/widgets/widgets/shapedclock/shapedclock.h +++ b/examples/widgets/widgets/shapedclock/shapedclock.h @@ -59,7 +59,7 @@ class ShapedClock : public QWidget Q_OBJECT public: - ShapedClock(QWidget *parent = 0); + ShapedClock(QWidget *parent = nullptr); QSize sizeHint() const override; protected: diff --git a/examples/widgets/widgets/sliders/slidersgroup.h b/examples/widgets/widgets/sliders/slidersgroup.h index 76dcbee0d8..7be8a3b4f8 100644 --- a/examples/widgets/widgets/sliders/slidersgroup.h +++ b/examples/widgets/widgets/sliders/slidersgroup.h @@ -66,7 +66,7 @@ class SlidersGroup : public QGroupBox public: SlidersGroup(Qt::Orientation orientation, const QString &title, - QWidget *parent = 0); + QWidget *parent = nullptr); signals: void valueChanged(int value); diff --git a/examples/widgets/widgets/styles/widgetgallery.h b/examples/widgets/widgets/styles/widgetgallery.h index ec6edff536..9ee65c21c4 100644 --- a/examples/widgets/widgets/styles/widgetgallery.h +++ b/examples/widgets/widgets/styles/widgetgallery.h @@ -78,7 +78,7 @@ class WidgetGallery : public QDialog Q_OBJECT public: - WidgetGallery(QWidget *parent = 0); + WidgetGallery(QWidget *parent = nullptr); private slots: void changeStyle(const QString &styleName); diff --git a/examples/widgets/widgets/stylesheet/stylesheeteditor.h b/examples/widgets/widgets/stylesheet/stylesheeteditor.h index 65a3018adb..f51af7877c 100644 --- a/examples/widgets/widgets/stylesheet/stylesheeteditor.h +++ b/examples/widgets/widgets/stylesheet/stylesheeteditor.h @@ -60,7 +60,7 @@ class StyleSheetEditor : public QDialog Q_OBJECT public: - StyleSheetEditor(QWidget *parent = 0); + StyleSheetEditor(QWidget *parent = nullptr); private slots: void on_styleCombo_activated(const QString &styleName); diff --git a/examples/widgets/widgets/tablet/tabletapplication.h b/examples/widgets/widgets/tablet/tabletapplication.h index 6b3b2a1730..9b4a4f1886 100644 --- a/examples/widgets/widgets/tablet/tabletapplication.h +++ b/examples/widgets/widgets/tablet/tabletapplication.h @@ -61,15 +61,14 @@ class TabletApplication : public QApplication Q_OBJECT public: - TabletApplication(int &argv, char **args) - : QApplication(argv, args) {} + using QApplication::QApplication; bool event(QEvent *event) override; void setCanvas(TabletCanvas *canvas) { m_canvas = canvas; } private: - TabletCanvas *m_canvas; + TabletCanvas *m_canvas = nullptr; }; //! [0] diff --git a/examples/widgets/widgets/tetrix/tetrixboard.h b/examples/widgets/widgets/tetrix/tetrixboard.h index 7c6871dfbd..86bcfa4d6e 100644 --- a/examples/widgets/widgets/tetrix/tetrixboard.h +++ b/examples/widgets/widgets/tetrix/tetrixboard.h @@ -67,7 +67,7 @@ class TetrixBoard : public QFrame Q_OBJECT public: - TetrixBoard(QWidget *parent = 0); + TetrixBoard(QWidget *parent = nullptr); void setNextPieceLabel(QLabel *label); QSize sizeHint() const override; diff --git a/examples/widgets/widgets/tooltips/sortingbox.cpp b/examples/widgets/widgets/tooltips/sortingbox.cpp index 766815e8e9..5f8d96f110 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.cpp +++ b/examples/widgets/widgets/tooltips/sortingbox.cpp @@ -64,7 +64,7 @@ SortingBox::SortingBox(QWidget *parent) setBackgroundRole(QPalette::Base); //! [2] - itemInMotion = 0; + itemInMotion = nullptr; //! [3] newCircleButton = createToolButton(tr("New Circle"), @@ -179,7 +179,7 @@ void SortingBox::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && itemInMotion) { moveItemTo(event->pos()); - itemInMotion = 0; + itemInMotion = nullptr; } } //! [13] diff --git a/examples/widgets/widgets/validators/ledwidget.h b/examples/widgets/widgets/validators/ledwidget.h index dcbfb176c2..c4b406db23 100644 --- a/examples/widgets/widgets/validators/ledwidget.h +++ b/examples/widgets/widgets/validators/ledwidget.h @@ -59,7 +59,7 @@ class LEDWidget : public QLabel { Q_OBJECT public: - LEDWidget(QWidget *parent = 0); + LEDWidget(QWidget *parent = nullptr); public slots: void flash(); diff --git a/examples/widgets/widgets/validators/localeselector.h b/examples/widgets/widgets/validators/localeselector.h index 05290eae81..611e2da66e 100644 --- a/examples/widgets/widgets/validators/localeselector.h +++ b/examples/widgets/widgets/validators/localeselector.h @@ -58,7 +58,7 @@ class LocaleSelector : public QComboBox Q_OBJECT public: - LocaleSelector(QWidget *parent = 0); + LocaleSelector(QWidget *parent = nullptr); signals: void localeSelected(const QLocale &locale); diff --git a/examples/widgets/widgets/wiggly/dialog.h b/examples/widgets/widgets/wiggly/dialog.h index a0981dc6b6..357b6354b5 100644 --- a/examples/widgets/widgets/wiggly/dialog.h +++ b/examples/widgets/widgets/wiggly/dialog.h @@ -59,7 +59,7 @@ class Dialog : public QDialog Q_OBJECT public: - explicit Dialog(QWidget *parent = 0); + explicit Dialog(QWidget *parent = nullptr); }; //! [0] diff --git a/examples/widgets/widgets/wiggly/wigglywidget.h b/examples/widgets/widgets/wiggly/wigglywidget.h index 58a7d045e1..1d909c34da 100644 --- a/examples/widgets/widgets/wiggly/wigglywidget.h +++ b/examples/widgets/widgets/wiggly/wigglywidget.h @@ -60,7 +60,7 @@ class WigglyWidget : public QWidget Q_OBJECT public: - WigglyWidget(QWidget *parent = 0); + WigglyWidget(QWidget *parent = nullptr); public slots: void setText(const QString &newText) { text = newText; } diff --git a/examples/widgets/widgets/windowflags/previewwindow.h b/examples/widgets/widgets/windowflags/previewwindow.h index e9efd09507..9bb487e8ab 100644 --- a/examples/widgets/widgets/windowflags/previewwindow.h +++ b/examples/widgets/widgets/windowflags/previewwindow.h @@ -64,7 +64,7 @@ class PreviewWindow : public QWidget Q_OBJECT public: - PreviewWindow(QWidget *parent = 0); + PreviewWindow(QWidget *parent = nullptr); void setWindowFlags(Qt::WindowFlags flags); -- cgit v1.2.3 From bce32c8ab8c547d0fc9d12d192546dde361443fa Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 11:58:03 +0100 Subject: Cleanup Widgets examples - foreach Cleanup the Widgets examples - replace foreach with range-based for loop in mainwindows and painting subdirectories Change-Id: I3c1556dffd22e29dd0a5ba960e699291c496278a Reviewed-by: Konstantin Shegunov Reviewed-by: Paul Wicking Reviewed-by: Luca Beldi Reviewed-by: Martin Smith --- .../widgets/mainwindows/mainwindow/colorswatch.cpp | 7 ++-- .../widgets/mainwindows/mainwindow/toolbar.cpp | 3 +- examples/widgets/mainwindows/mdi/main.cpp | 3 +- examples/widgets/mainwindows/mdi/mainwindow.cpp | 3 +- examples/widgets/mainwindows/sdi/main.cpp | 3 +- examples/widgets/mainwindows/sdi/mainwindow.cpp | 3 +- examples/widgets/painting/affine/main.cpp | 8 ++-- examples/widgets/painting/composition/main.cpp | 4 +- examples/widgets/painting/deform/main.cpp | 8 ++-- examples/widgets/painting/deform/pathdeform.cpp | 8 ++-- examples/widgets/painting/deform/pathdeform.h | 4 +- .../widgets/painting/fontsampler/mainwindow.cpp | 31 ++++++++------- examples/widgets/painting/gradients/main.cpp | 4 +- examples/widgets/painting/painterpaths/window.cpp | 4 +- examples/widgets/painting/pathstroke/main.cpp | 4 +- .../widgets/painting/pathstroke/pathstroke.cpp | 6 +-- examples/widgets/painting/shared/arthurwidgets.cpp | 46 ++++++++++++---------- examples/widgets/painting/shared/hoverpoints.cpp | 2 +- 18 files changed, 82 insertions(+), 69 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp index 240a04c897..4e4c15ccaf 100644 --- a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp +++ b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp @@ -454,8 +454,8 @@ void ColorSwatch::updateContextMenu() tabMenu->clear(); splitHMenu->clear(); splitVMenu->clear(); - QList dock_list = mainWindow->findChildren(); - foreach (ColorSwatch *dock, dock_list) { + const QList dockList = mainWindow->findChildren(); + for (const ColorSwatch *dock : dockList) { tabMenu->addAction(dock->objectName()); splitHMenu->addAction(dock->objectName()); splitVMenu->addAction(dock->objectName()); @@ -464,7 +464,8 @@ void ColorSwatch::updateContextMenu() static ColorSwatch *findByName(const QMainWindow *mainWindow, const QString &name) { - foreach (ColorSwatch *dock, mainWindow->findChildren()) { + const QList dockList = mainWindow->findChildren(); + for (ColorSwatch *dock : dockList) { if (name == dock->objectName()) return dock; } diff --git a/examples/widgets/mainwindows/mainwindow/toolbar.cpp b/examples/widgets/mainwindows/mainwindow/toolbar.cpp index 096d3df5a8..36d4108b1e 100644 --- a/examples/widgets/mainwindows/mainwindow/toolbar.cpp +++ b/examples/widgets/mainwindows/mainwindow/toolbar.cpp @@ -244,7 +244,8 @@ void ToolBar::order() { QList ordered; QList actions1 = actions(); - foreach (QAction *action, findChildren()) { + const QList childActions = findChildren(); + for (QAction *action : childActions) { if (!actions1.contains(action)) continue; actions1.removeAll(action); diff --git a/examples/widgets/mainwindows/mdi/main.cpp b/examples/widgets/mainwindows/mdi/main.cpp index e23f5f6e60..950244ad53 100644 --- a/examples/widgets/mainwindows/mdi/main.cpp +++ b/examples/widgets/mainwindows/mdi/main.cpp @@ -70,7 +70,8 @@ int main(int argc, char *argv[]) parser.process(app); MainWindow mainWin; - foreach (const QString &fileName, parser.positionalArguments()) + const QStringList posArgs = parser.positionalArguments(); + for (const QString &fileName : posArgs) mainWin.openFile(fileName); mainWin.show(); return app.exec(); diff --git a/examples/widgets/mainwindows/mdi/mainwindow.cpp b/examples/widgets/mainwindows/mdi/mainwindow.cpp index 1e87c5a747..b952d19e2e 100644 --- a/examples/widgets/mainwindows/mdi/mainwindow.cpp +++ b/examples/widgets/mainwindows/mdi/mainwindow.cpp @@ -490,7 +490,8 @@ QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName) const { QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath(); - foreach (QMdiSubWindow *window, mdiArea->subWindowList()) { + const QList subWindows = mdiArea->subWindowList(); + for (QMdiSubWindow *window : subWindows) { MdiChild *mdiChild = qobject_cast(window->widget()); if (mdiChild->currentFile() == canonicalFilePath) return window; diff --git a/examples/widgets/mainwindows/sdi/main.cpp b/examples/widgets/mainwindows/sdi/main.cpp index 6e29fafd6f..7a18c0c39c 100644 --- a/examples/widgets/mainwindows/sdi/main.cpp +++ b/examples/widgets/mainwindows/sdi/main.cpp @@ -68,7 +68,8 @@ int main(int argc, char *argv[]) parser.process(app); MainWindow *mainWin = nullptr; - foreach (const QString &file, parser.positionalArguments()) { + const QStringList posArgs = parser.positionalArguments(); + for (const QString &file : posArgs) { MainWindow *newWin = new MainWindow(file); newWin->tile(mainWin); newWin->show(); diff --git a/examples/widgets/mainwindows/sdi/mainwindow.cpp b/examples/widgets/mainwindows/sdi/mainwindow.cpp index f3e3af8a1b..62a74b26e6 100644 --- a/examples/widgets/mainwindows/sdi/mainwindow.cpp +++ b/examples/widgets/mainwindows/sdi/mainwindow.cpp @@ -472,7 +472,8 @@ MainWindow *MainWindow::findMainWindow(const QString &fileName) const { QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath(); - foreach (QWidget *widget, QApplication::topLevelWidgets()) { + const QList topLevelWidgets = QApplication::topLevelWidgets(); + for (QWidget *widget : topLevelWidgets) { MainWindow *mainWin = qobject_cast(widget); if (mainWin && mainWin->curFile == canonicalFilePath) return mainWin; diff --git a/examples/widgets/painting/affine/main.cpp b/examples/widgets/painting/affine/main.cpp index a820c784f0..6ce8efe482 100644 --- a/examples/widgets/painting/affine/main.cpp +++ b/examples/widgets/painting/affine/main.cpp @@ -58,12 +58,12 @@ int main(int argc, char **argv) QApplication app(argc, argv); - XFormWidget xformWidget(0); - QStyle *arthurStyle = new ArthurStyle(); + XFormWidget xformWidget(nullptr); + QStyle *arthurStyle = new ArthurStyle; xformWidget.setStyle(arthurStyle); - QList widgets = xformWidget.findChildren(); - foreach (QWidget *w, widgets) { + const QList widgets = xformWidget.findChildren(); + for (QWidget *w : widgets) { w->setStyle(arthurStyle); w->setAttribute(Qt::WA_AcceptTouchEvents); } diff --git a/examples/widgets/painting/composition/main.cpp b/examples/widgets/painting/composition/main.cpp index 1f4ead7165..2eaeaba2c5 100644 --- a/examples/widgets/painting/composition/main.cpp +++ b/examples/widgets/painting/composition/main.cpp @@ -60,8 +60,8 @@ int main(int argc, char *argv[]) QStyle *arthurStyle = new ArthurStyle(); compWidget.setStyle(arthurStyle); - QList widgets = compWidget.findChildren(); - foreach (QWidget *w, widgets) + const QList widgets = compWidget.findChildren(); + for (QWidget *w : widgets) w->setStyle(arthurStyle); compWidget.show(); diff --git a/examples/widgets/painting/deform/main.cpp b/examples/widgets/painting/deform/main.cpp index 85e83207c0..28e3d6823d 100644 --- a/examples/widgets/painting/deform/main.cpp +++ b/examples/widgets/painting/deform/main.cpp @@ -60,12 +60,12 @@ int main(int argc, char **argv) bool smallScreen = QApplication::arguments().contains("-small-screen"); - PathDeformWidget deformWidget(0, smallScreen); + PathDeformWidget deformWidget(nullptr, smallScreen); - QStyle *arthurStyle = new ArthurStyle(); + QStyle *arthurStyle = new ArthurStyle; deformWidget.setStyle(arthurStyle); - QList widgets = deformWidget.findChildren(); - foreach (QWidget *w, widgets) + const QList widgets = deformWidget.findChildren(); + for (QWidget *w : widgets) w->setStyle(arthurStyle); if (smallScreen) diff --git a/examples/widgets/painting/deform/pathdeform.cpp b/examples/widgets/painting/deform/pathdeform.cpp index 3b80c40e9b..0eda76a831 100644 --- a/examples/widgets/painting/deform/pathdeform.cpp +++ b/examples/widgets/painting/deform/pathdeform.cpp @@ -291,16 +291,16 @@ void PathDeformWidget::hideControls() m_controls->hide(); } -void PathDeformWidget::setStyle( QStyle * style ) +void PathDeformWidget::setStyle(QStyle *style) { QWidget::setStyle(style); - if (m_controls == 0) + if (!m_controls) return; m_controls->setStyle(style); - QList widgets = m_controls->findChildren(); - foreach (QWidget *w, widgets) + const QList widgets = m_controls->findChildren(); + for (QWidget *w : widgets) w->setStyle(style); } diff --git a/examples/widgets/painting/deform/pathdeform.h b/examples/widgets/painting/deform/pathdeform.h index 68908045b9..b7c7386e2a 100644 --- a/examples/widgets/painting/deform/pathdeform.h +++ b/examples/widgets/painting/deform/pathdeform.h @@ -135,7 +135,7 @@ signals: void okPressed(); void quitPressed(); private: - PathDeformRenderer* m_renderer; + PathDeformRenderer *m_renderer; void layoutForDesktop(); void layoutForSmallScreen(); }; @@ -145,7 +145,7 @@ class PathDeformWidget : public QWidget Q_OBJECT public: PathDeformWidget(QWidget *parent, bool smallScreen); - void setStyle (QStyle * style ); + void setStyle(QStyle *style); private: PathDeformRenderer *m_renderer; diff --git a/examples/widgets/painting/fontsampler/mainwindow.cpp b/examples/widgets/painting/fontsampler/mainwindow.cpp index 6344806f29..a464eee3ff 100644 --- a/examples/widgets/painting/fontsampler/mainwindow.cpp +++ b/examples/widgets/painting/fontsampler/mainwindow.cpp @@ -86,9 +86,10 @@ void MainWindow::setupFontTree() { QFontDatabase database; fontTree->setColumnCount(1); - fontTree->setHeaderLabels(QStringList() << tr("Font")); + fontTree->setHeaderLabels({ tr("Font") }); - foreach (QString family, database.families()) { + const QStringList fontFamilies = database.families(); + for (const QString &family : fontFamilies) { const QStringList styles = database.styles(family); if (styles.isEmpty()) continue; @@ -98,7 +99,7 @@ void MainWindow::setupFontTree() familyItem->setCheckState(0, Qt::Unchecked); familyItem->setFlags(familyItem->flags() | Qt::ItemIsAutoTristate); - foreach (QString style, styles) { + for (const QString &style : styles) { QTreeWidgetItem *styleItem = new QTreeWidgetItem(familyItem); styleItem->setText(0, style); styleItem->setCheckState(0, Qt::Unchecked); @@ -110,10 +111,10 @@ void MainWindow::setupFontTree() void MainWindow::on_clearAction_triggered() { - QTreeWidgetItem *currentItem = fontTree->currentItem(); - foreach (QTreeWidgetItem *item, fontTree->selectedItems()) - fontTree->setItemSelected(item, false); - fontTree->setItemSelected(currentItem, true); + const QList items = fontTree->selectedItems(); + for (QTreeWidgetItem *item : items) + item->setSelected(false); + fontTree->currentItem()->setSelected(true); } void MainWindow::on_markAction_triggered() @@ -128,8 +129,8 @@ void MainWindow::on_unmarkAction_triggered() void MainWindow::markUnmarkFonts(Qt::CheckState state) { - QList items = fontTree->selectedItems(); - foreach (QTreeWidgetItem *item, items) { + const QList items = fontTree->selectedItems(); + for (QTreeWidgetItem *item : items) { if (item->checkState(0) != state) item->setCheckState(0, state); } @@ -295,19 +296,19 @@ void MainWindow::on_printPreviewAction_triggered() void MainWindow::printPage(int index, QPainter *painter, QPrinter *printer) { #if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printdialog) - QString family = pageMap.keys()[index]; - StyleItems items = pageMap[family]; + const QString family = (pageMap.begin() + index).key(); + const StyleItems items = pageMap.value(family); // Find the dimensions of the text on each page. qreal width = 0.0; qreal height = 0.0; - foreach (QTreeWidgetItem *item, items) { + for (const QTreeWidgetItem *item : items) { QString style = item->text(0); int weight = item->data(0, Qt::UserRole).toInt(); bool italic = item->data(0, Qt::UserRole + 1).toBool(); // Calculate the maximum width and total height of the text. - foreach (int size, sampleSizes) { + for (int size : qAsConst(sampleSizes)) { QFont font(family, size, weight, italic); font.setStyleName(style); font = QFont(font, painter->device()); @@ -335,13 +336,13 @@ void MainWindow::printPage(int index, QPainter *painter, QPrinter *printer) qreal x = -width / 2.0; qreal y = -height / 2.0 - remainingHeight / 4.0 + spaceHeight; - foreach (QTreeWidgetItem *item, items) { + for (const QTreeWidgetItem *item : items) { QString style = item->text(0); int weight = item->data(0, Qt::UserRole).toInt(); bool italic = item->data(0, Qt::UserRole + 1).toBool(); // Draw each line of text. - foreach (int size, sampleSizes) { + for (int size : qAsConst(sampleSizes)) { QFont font(family, size, weight, italic); font.setStyleName(style); font = QFont(font, painter->device()); diff --git a/examples/widgets/painting/gradients/main.cpp b/examples/widgets/painting/gradients/main.cpp index 6c5261fe6b..539d67e40e 100644 --- a/examples/widgets/painting/gradients/main.cpp +++ b/examples/widgets/painting/gradients/main.cpp @@ -61,8 +61,8 @@ int main(int argc, char *argv[]) GradientWidget gradientWidget(0); QStyle *arthurStyle = new ArthurStyle(); gradientWidget.setStyle(arthurStyle); - QList widgets = gradientWidget.findChildren(); - foreach (QWidget *w, widgets) { + const QList widgets = gradientWidget.findChildren(); + for (QWidget *w : widgets) { w->setStyle(arthurStyle); w->setAttribute(Qt::WA_AcceptTouchEvents); } diff --git a/examples/widgets/painting/painterpaths/window.cpp b/examples/widgets/painting/painterpaths/window.cpp index 95e312623e..6fb3218313 100644 --- a/examples/widgets/painting/painterpaths/window.cpp +++ b/examples/widgets/painting/painterpaths/window.cpp @@ -280,8 +280,8 @@ void Window::penColorChanged() //! [22] void Window::populateWithColors(QComboBox *comboBox) { - QStringList colorNames = QColor::colorNames(); - foreach (QString name, colorNames) + const QStringList colorNames = QColor::colorNames(); + for (const QString &name : colorNames) comboBox->addItem(name, QColor(name)); } //! [22] diff --git a/examples/widgets/painting/pathstroke/main.cpp b/examples/widgets/painting/pathstroke/main.cpp index 3a63203118..57c85d73a3 100644 --- a/examples/widgets/painting/pathstroke/main.cpp +++ b/examples/widgets/painting/pathstroke/main.cpp @@ -63,8 +63,8 @@ int main(int argc, char **argv) PathStrokeWidget pathStrokeWidget(smallScreen); QStyle *arthurStyle = new ArthurStyle(); pathStrokeWidget.setStyle(arthurStyle); - QList widgets = pathStrokeWidget.findChildren(); - foreach (QWidget *w, widgets) { + const QList widgets = pathStrokeWidget.findChildren(); + for (QWidget *w : widgets) { w->setStyle(arthurStyle); w->setAttribute(Qt::WA_AcceptTouchEvents); } diff --git a/examples/widgets/painting/pathstroke/pathstroke.cpp b/examples/widgets/painting/pathstroke/pathstroke.cpp index acb946496f..cad0b8732c 100644 --- a/examples/widgets/painting/pathstroke/pathstroke.cpp +++ b/examples/widgets/painting/pathstroke/pathstroke.cpp @@ -390,8 +390,8 @@ void PathStrokeWidget::setStyle( QStyle * style ) { m_controls->setStyle(style); - QList widgets = m_controls->findChildren(); - foreach (QWidget *w, widgets) + const QList widgets = m_controls->findChildren(); + for (QWidget *w : widgets) w->setStyle(style); } } @@ -605,7 +605,7 @@ bool PathStrokeRenderer::event(QEvent *e) { const QTouchEvent *const event = static_cast(e); const QList points = event->touchPoints(); - foreach (const QTouchEvent::TouchPoint &touchPoint, points) { + for (const QTouchEvent::TouchPoint &touchPoint : points) { const int id = touchPoint.id(); switch (touchPoint.state()) { case Qt::TouchPointPressed: diff --git a/examples/widgets/painting/shared/arthurwidgets.cpp b/examples/widgets/painting/shared/arthurwidgets.cpp index 442fb69ac1..bdac5de13c 100644 --- a/examples/widgets/painting/shared/arthurwidgets.cpp +++ b/examples/widgets/painting/shared/arthurwidgets.cpp @@ -330,32 +330,40 @@ void ArthurFrame::showSource() QString contents; if (m_sourceFileName.isEmpty()) { - contents = QString("No source for widget: '%1'").arg(objectName()); + contents = tr("No source for widget: '%1'").arg(objectName()); } else { QFile f(m_sourceFileName); if (!f.open(QFile::ReadOnly)) - contents = QString("Could not open file: '%1'").arg(m_sourceFileName); + contents = tr("Could not open file: '%1'").arg(m_sourceFileName); else contents = f.readAll(); } - contents.replace('&', "&"); - contents.replace('<', "<"); - contents.replace('>', ">"); - - QStringList keywords; - keywords << "for " << "if " << "switch " << " int " << "#include " << "const" - << "void " << "uint " << "case " << "double " << "#define " << "static" - << "new" << "this"; - - foreach (QString keyword, keywords) + contents.replace(QLatin1Char('&'), QStringLiteral("&")); + contents.replace(QLatin1Char('<'), QStringLiteral("<")); + contents.replace(QLatin1Char('>'), QStringLiteral(">")); + + static const QString keywords[] = { + QStringLiteral("for "), QStringLiteral("if "), + QStringLiteral("switch "), QStringLiteral(" int "), + QStringLiteral("#include "), QStringLiteral("const"), + QStringLiteral("void "), QStringLiteral("uint "), + QStringLiteral("case "), QStringLiteral("double "), + QStringLiteral("#define "), QStringLiteral("static"), + QStringLiteral("new"), QStringLiteral("this") + }; + + for (const QString &keyword : keywords) contents.replace(keyword, QLatin1String("") + keyword + QLatin1String("")); - contents.replace("(int ", "(int "); + contents.replace(QStringLiteral("(int "), QStringLiteral("(int ")); - QStringList ppKeywords; - ppKeywords << "#ifdef" << "#ifndef" << "#if" << "#endif" << "#else"; + static const QString ppKeywords[] = { + QStringLiteral("#ifdef"), QStringLiteral("#ifndef"), + QStringLiteral("#if"), QStringLiteral("#endif"), + QStringLiteral("#else") + }; - foreach (QString keyword, ppKeywords) + for (const QString &keyword : ppKeywords) contents.replace(keyword, QLatin1String("") + keyword + QLatin1String("")); contents.replace(QRegularExpression("(\\d\\d?)"), QLatin1String("\\1")); @@ -366,12 +374,10 @@ void ArthurFrame::showSource() QRegularExpression stringLiteralRe("(\".+?\")"); contents.replace(stringLiteralRe, QLatin1String("\\1")); - QString html = contents; - html.prepend("
");
-    html.append("
"); + const QString html = QStringLiteral("
") + contents + QStringLiteral("
"); QTextBrowser *sourceViewer = new QTextBrowser(0); - sourceViewer->setWindowTitle("Source: " + m_sourceFileName.mid(5)); + sourceViewer->setWindowTitle(tr("Source: %1").arg(m_sourceFileName.midRef(5))); sourceViewer->setParent(this, Qt::Dialog); sourceViewer->setAttribute(Qt::WA_DeleteOnClose); sourceViewer->setLineWrapMode(QTextEdit::NoWrap); diff --git a/examples/widgets/painting/shared/hoverpoints.cpp b/examples/widgets/painting/shared/hoverpoints.cpp index a16bda4835..74c78088ad 100644 --- a/examples/widgets/painting/shared/hoverpoints.cpp +++ b/examples/widgets/painting/shared/hoverpoints.cpp @@ -174,7 +174,7 @@ bool HoverPoints::eventFilter(QObject *object, QEvent *event) const QTouchEvent *const touchEvent = static_cast(event); const QList points = touchEvent->touchPoints(); const qreal pointSize = qMax(m_pointSize.width(), m_pointSize.height()); - foreach (const QTouchEvent::TouchPoint &touchPoint, points) { + for (const QTouchEvent::TouchPoint &touchPoint : points) { const int id = touchPoint.id(); switch (touchPoint.state()) { case Qt::TouchPointPressed: -- cgit v1.2.3 From 26f7edb09eaf66590de9a3603489464fd868eedc Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 11:59:02 +0100 Subject: Cleanup Widgets examples - foreach Cleanup the Widgets examples - replace foreach with range-based for loop in graphicsview subdirectory Change-Id: I9093b3ae89d73d0b860d29929943881c90074bce Reviewed-by: Luca Beldi Reviewed-by: Paul Wicking --- examples/widgets/graphicsview/boxes/glbuffers.cpp | 4 +- examples/widgets/graphicsview/boxes/glbuffers.h | 2 +- examples/widgets/graphicsview/boxes/qtbox.cpp | 24 ++++------ examples/widgets/graphicsview/boxes/scene.cpp | 56 ++++++++-------------- .../widgets/graphicsview/collidingmice/mouse.cpp | 11 +++-- .../graphicsview/diagramscene/diagramitem.cpp | 5 +- .../graphicsview/diagramscene/diagramscene.cpp | 10 ++-- .../graphicsview/diagramscene/diagramscene.h | 2 +- .../graphicsview/diagramscene/mainwindow.cpp | 22 +++++---- .../graphicsview/elasticnodes/graphwidget.cpp | 10 ++-- .../widgets/graphicsview/elasticnodes/node.cpp | 7 +-- .../embeddeddialogs/embeddeddialog.cpp | 6 ++- .../widgets/graphicsview/flowlayout/flowlayout.cpp | 9 ++-- 13 files changed, 74 insertions(+), 94 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/graphicsview/boxes/glbuffers.cpp b/examples/widgets/graphicsview/boxes/glbuffers.cpp index 851cd17796..b52b26c4ef 100644 --- a/examples/widgets/graphicsview/boxes/glbuffers.cpp +++ b/examples/widgets/graphicsview/boxes/glbuffers.cpp @@ -218,14 +218,14 @@ GLTextureCube::GLTextureCube(int size) glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } -GLTextureCube::GLTextureCube(const QStringList& fileNames, int size) +GLTextureCube::GLTextureCube(const QStringList &fileNames, int size) { // TODO: Add error handling. glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); int index = 0; - foreach (QString file, fileNames) { + for (const QString &file : fileNames) { QImage image(file); if (image.isNull()) { m_failed = true; diff --git a/examples/widgets/graphicsview/boxes/glbuffers.h b/examples/widgets/graphicsview/boxes/glbuffers.h index 03c24a91d3..e2363d561e 100644 --- a/examples/widgets/graphicsview/boxes/glbuffers.h +++ b/examples/widgets/graphicsview/boxes/glbuffers.h @@ -129,7 +129,7 @@ class GLTextureCube : public GLTexture { public: GLTextureCube(int size); - explicit GLTextureCube(const QStringList& fileNames, int size = 0); + explicit GLTextureCube(const QStringList &fileNames, int size = 0); void load(int size, int face, QRgb *data); void bind() override; void unbind() override; diff --git a/examples/widgets/graphicsview/boxes/qtbox.cpp b/examples/widgets/graphicsview/boxes/qtbox.cpp index 3a184dd0b6..68d5c251f4 100644 --- a/examples/widgets/graphicsview/boxes/qtbox.cpp +++ b/examples/widgets/graphicsview/boxes/qtbox.cpp @@ -127,10 +127,8 @@ void ItemBase::duplicateSelectedItems(QGraphicsScene *scene) if (!scene) return; - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { + const QList selected = scene->selectedItems(); + for (QGraphicsItem *item : selected) { ItemBase *itemBase = qgraphicsitem_cast(item); if (itemBase) scene->addItem(itemBase->createNew(itemBase->m_size, itemBase->pos().x() + itemBase->m_size, itemBase->pos().y())); @@ -142,10 +140,8 @@ void ItemBase::deleteSelectedItems(QGraphicsScene *scene) if (!scene) return; - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { + const QList selected = scene->selectedItems(); + for (QGraphicsItem *item : selected) { ItemBase *itemBase = qgraphicsitem_cast(item); if (itemBase) delete itemBase; @@ -157,10 +153,8 @@ void ItemBase::growSelectedItems(QGraphicsScene *scene) if (!scene) return; - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { + const QList selected = scene->selectedItems(); + for (QGraphicsItem *item : selected) { ItemBase *itemBase = qgraphicsitem_cast(item); if (itemBase) { itemBase->prepareGeometryChange(); @@ -176,10 +170,8 @@ void ItemBase::shrinkSelectedItems(QGraphicsScene *scene) if (!scene) return; - QList selected; - selected = scene->selectedItems(); - - foreach (QGraphicsItem *item, selected) { + const QList selected = scene->selectedItems(); + for (QGraphicsItem *item : selected) { ItemBase *itemBase = qgraphicsitem_cast(item); if (itemBase) { itemBase->prepareGeometryChange(); diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp index 3c65206c02..7f62ac894b 100644 --- a/examples/widgets/graphicsview/boxes/scene.cpp +++ b/examples/widgets/graphicsview/boxes/scene.cpp @@ -311,15 +311,13 @@ RenderOptionsDialog::RenderOptionsDialog() layout->addWidget(check, 0, 0, 1, 2); ++row; - QPalette palette; - // Load all .par files // .par files have a simple syntax for specifying user adjustable uniform variables. - QSet uniforms; - QList filter = QStringList("*.par"); - QList files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + const QList files = QDir(QStringLiteral(":/res/boxes/")) + .entryInfoList({ QStringLiteral("*.par") }, + QDir::Files | QDir::Readable); - foreach (QFileInfo fileInfo, files) { + for (const QFileInfo &fileInfo : files) { QFile file(fileInfo.absoluteFilePath()); if (file.open(QIODevice::ReadOnly)) { while (!file.atEnd()) { @@ -404,7 +402,7 @@ int RenderOptionsDialog::addShader(const QString &name) void RenderOptionsDialog::emitParameterChanged() { - foreach (ParameterEdit *edit, m_parameterEdits) + for (ParameterEdit *edit : qAsConst(m_parameterEdits)) edit->emitChange(); } @@ -541,24 +539,15 @@ Scene::Scene(int width, int height, int maxTextureSize) Scene::~Scene() { - if (m_box) - delete m_box; - foreach (GLTexture *texture, m_textures) - if (texture) delete texture; - if (m_mainCubemap) - delete m_mainCubemap; - foreach (QGLShaderProgram *program, m_programs) - if (program) delete program; - if (m_vertexShader) - delete m_vertexShader; - foreach (QGLShader *shader, m_fragmentShaders) - if (shader) delete shader; - foreach (GLRenderTargetCube *rt, m_cubemaps) - if (rt) delete rt; - if (m_environmentShader) - delete m_environmentShader; - if (m_environmentProgram) - delete m_environmentProgram; + delete m_box; + qDeleteAll(m_textures); + delete m_mainCubemap; + qDeleteAll(m_programs); + delete m_vertexShader; + qDeleteAll(m_fragmentShaders); + qDeleteAll(m_cubemaps); + delete m_environmentShader; + delete m_environmentProgram; } void Scene::initGL() @@ -603,15 +592,13 @@ void Scene::initGL() m_mainCubemap = new GLRenderTargetCube(512); - QStringList filter; QList files; // Load all .png files as textures m_currentTexture = 0; - filter = QStringList("*.png"); - files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + files = QDir(":/res/boxes/").entryInfoList({ QStringLiteral("*.png") }, QDir::Files | QDir::Readable); - foreach (QFileInfo file, files) { + for (const QFileInfo &file : qAsConst(files)) { GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize)); if (texture->failed()) { delete texture; @@ -626,9 +613,8 @@ void Scene::initGL() // Load all .fsh files as fragment shaders m_currentShader = 0; - filter = QStringList("*.fsh"); - files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); - foreach (QFileInfo file, files) { + files = QDir(":/res/boxes/").entryInfoList({ QStringLiteral("*.fsh") }, QDir::Files | QDir::Readable); + for (const QFileInfo &file : qAsConst(files)) { QGLShaderProgram *program = new QGLShaderProgram; QGLShader* shader = new QGLShader(QGLShader::Fragment); shader->compileSourceFile(file.absoluteFilePath()); @@ -664,7 +650,7 @@ void Scene::initGL() m_renderOptions->emitParameterChanged(); } -static void loadMatrix(const QMatrix4x4& m) +static void loadMatrix(const QMatrix4x4 &m) { // static to prevent glLoadMatrixf to fail on certain drivers static GLfloat mat[16]; @@ -1053,7 +1039,7 @@ void Scene::toggleDynamicCubemap(int state) void Scene::setColorParameter(const QString &name, QRgb color) { // set the color in all programs - foreach (QGLShaderProgram *program, m_programs) { + for (QGLShaderProgram *program : qAsConst(m_programs)) { program->bind(); program->setUniformValue(program->uniformLocation(name), QColor(color)); program->release(); @@ -1063,7 +1049,7 @@ void Scene::setColorParameter(const QString &name, QRgb color) void Scene::setFloatParameter(const QString &name, float value) { // set the color in all programs - foreach (QGLShaderProgram *program, m_programs) { + for (QGLShaderProgram *program : qAsConst(m_programs)) { program->bind(); program->setUniformValue(program->uniformLocation(name), value); program->release(); diff --git a/examples/widgets/graphicsview/collidingmice/mouse.cpp b/examples/widgets/graphicsview/collidingmice/mouse.cpp index 14f887f6e3..a8fcc05d76 100644 --- a/examples/widgets/graphicsview/collidingmice/mouse.cpp +++ b/examples/widgets/graphicsview/collidingmice/mouse.cpp @@ -160,11 +160,12 @@ void Mouse::advance(int step) // Try not to crash with any other mice //! [7] - QList dangerMice = scene()->items(QPolygonF() - << mapToScene(0, 0) - << mapToScene(-30, -50) - << mapToScene(30, -50)); - foreach (QGraphicsItem *item, dangerMice) { + const QList dangerMice = scene()->items(QPolygonF() + << mapToScene(0, 0) + << mapToScene(-30, -50) + << mapToScene(30, -50)); + + for (const QGraphicsItem *item : dangerMice) { if (item == this) continue; diff --git a/examples/widgets/graphicsview/diagramscene/diagramitem.cpp b/examples/widgets/graphicsview/diagramscene/diagramitem.cpp index db6dabee56..3aa685635e 100644 --- a/examples/widgets/graphicsview/diagramscene/diagramitem.cpp +++ b/examples/widgets/graphicsview/diagramscene/diagramitem.cpp @@ -111,7 +111,7 @@ void DiagramItem::removeArrow(Arrow *arrow) //! [2] void DiagramItem::removeArrows() { - foreach (Arrow *arrow, arrows) { + for (Arrow *arrow : qAsConst(arrows)) { arrow->startItem()->removeArrow(arrow); arrow->endItem()->removeArrow(arrow); scene()->removeItem(arrow); @@ -154,9 +154,8 @@ void DiagramItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) QVariant DiagramItem::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == QGraphicsItem::ItemPositionChange) { - foreach (Arrow *arrow, arrows) { + for (Arrow *arrow : qAsConst(arrows)) arrow->updatePosition(); - } } return value; diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.cpp b/examples/widgets/graphicsview/diagramscene/diagramscene.cpp index 51d855cc75..40272834c3 100644 --- a/examples/widgets/graphicsview/diagramscene/diagramscene.cpp +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.cpp @@ -234,12 +234,10 @@ void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) //! [13] //! [14] -bool DiagramScene::isItemChange(int type) +bool DiagramScene::isItemChange(int type) const { - foreach (QGraphicsItem *item, selectedItems()) { - if (item->type() == type) - return true; - } - return false; + const QList items = selectedItems(); + const auto cb = [type](const QGraphicsItem *item) { return item->type() == type; }; + return std::find_if(items.begin(), items.end(), cb) != items.end(); } //! [14] diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.h b/examples/widgets/graphicsview/diagramscene/diagramscene.h index 95f7f3c621..15063d58b7 100644 --- a/examples/widgets/graphicsview/diagramscene/diagramscene.h +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.h @@ -100,7 +100,7 @@ protected: void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) override; private: - bool isItemChange(int type); + bool isItemChange(int type) const; DiagramItem::DiagramType myItemType; QMenu *myItemMenu; diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp index 875c41b284..07f92f61c1 100644 --- a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp +++ b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp @@ -92,8 +92,8 @@ MainWindow::MainWindow() //! [1] void MainWindow::backgroundButtonGroupClicked(QAbstractButton *button) { - QList buttons = backgroundButtonGroup->buttons(); - foreach (QAbstractButton *myButton, buttons) { + const QList buttons = backgroundButtonGroup->buttons(); + for (QAbstractButton *myButton : buttons) { if (myButton != button) button->setChecked(false); } @@ -115,8 +115,8 @@ void MainWindow::backgroundButtonGroupClicked(QAbstractButton *button) //! [2] void MainWindow::buttonGroupClicked(int id) { - QList buttons = buttonGroup->buttons(); - foreach (QAbstractButton *button, buttons) { + const QList buttons = buttonGroup->buttons(); + for (QAbstractButton *button : buttons) { if (buttonGroup->button(id) != button) button->setChecked(false); } @@ -132,7 +132,8 @@ void MainWindow::buttonGroupClicked(int id) //! [3] void MainWindow::deleteItem() { - foreach (QGraphicsItem *item, scene->selectedItems()) { + QList selectedItems = scene->selectedItems(); + for (QGraphicsItem *item : qAsConst(selectedItems)) { if (item->type() == Arrow::Type) { scene->removeItem(item); Arrow *arrow = qgraphicsitem_cast(item); @@ -142,7 +143,8 @@ void MainWindow::deleteItem() } } - foreach (QGraphicsItem *item, scene->selectedItems()) { + selectedItems = scene->selectedItems(); + for (QGraphicsItem *item : qAsConst(selectedItems)) { if (item->type() == DiagramItem::Type) qgraphicsitem_cast(item)->removeArrows(); scene->removeItem(item); @@ -165,10 +167,10 @@ void MainWindow::bringToFront() return; QGraphicsItem *selectedItem = scene->selectedItems().first(); - QList overlapItems = selectedItem->collidingItems(); + const QList overlapItems = selectedItem->collidingItems(); qreal zValue = 0; - foreach (QGraphicsItem *item, overlapItems) { + for (const QGraphicsItem *item : overlapItems) { if (item->zValue() >= zValue && item->type() == DiagramItem::Type) zValue = item->zValue() + 0.1; } @@ -183,10 +185,10 @@ void MainWindow::sendToBack() return; QGraphicsItem *selectedItem = scene->selectedItems().first(); - QList overlapItems = selectedItem->collidingItems(); + const QList overlapItems = selectedItem->collidingItems(); qreal zValue = 0; - foreach (QGraphicsItem *item, overlapItems) { + for (const QGraphicsItem *item : overlapItems) { if (item->zValue() <= zValue && item->type() == DiagramItem::Type) zValue = item->zValue() - 0.1; } diff --git a/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp b/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp index 81928a4ee1..6b817b2a21 100644 --- a/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp +++ b/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp @@ -164,16 +164,17 @@ void GraphWidget::timerEvent(QTimerEvent *event) Q_UNUSED(event); QList nodes; - foreach (QGraphicsItem *item, scene()->items()) { + const QList items = scene()->items(); + for (QGraphicsItem *item : items) { if (Node *node = qgraphicsitem_cast(item)) nodes << node; } - foreach (Node *node, nodes) + for (Node *node : qAsConst(nodes)) node->calculateForces(); bool itemsMoved = false; - foreach (Node *node, nodes) { + for (Node *node : qAsConst(nodes)) { if (node->advancePosition()) itemsMoved = true; } @@ -246,7 +247,8 @@ void GraphWidget::scaleView(qreal scaleFactor) void GraphWidget::shuffle() { - foreach (QGraphicsItem *item, scene()->items()) { + const QList items = scene()->items(); + for (QGraphicsItem *item : items) { if (qgraphicsitem_cast(item)) item->setPos(-150 + QRandomGenerator::global()->bounded(300), -150 + QRandomGenerator::global()->bounded(300)); } diff --git a/examples/widgets/graphicsview/elasticnodes/node.cpp b/examples/widgets/graphicsview/elasticnodes/node.cpp index 71737c984b..d4fa3d2b4f 100644 --- a/examples/widgets/graphicsview/elasticnodes/node.cpp +++ b/examples/widgets/graphicsview/elasticnodes/node.cpp @@ -94,7 +94,8 @@ void Node::calculateForces() // Sum up all forces pushing this item away qreal xvel = 0; qreal yvel = 0; - foreach (QGraphicsItem *item, scene()->items()) { + const QList items = scene()->items(); + for (QGraphicsItem *item : items) { Node *node = qgraphicsitem_cast(item); if (!node) continue; @@ -113,7 +114,7 @@ void Node::calculateForces() //! [4] // Now subtract all forces pulling items together double weight = (edgeList.size() + 1) * 10; - foreach (Edge *edge, edgeList) { + for (const Edge *edge : qAsConst(edgeList)) { QPointF vec; if (edge->sourceNode() == this) vec = mapToItem(edge->destNode(), 0, 0); @@ -194,7 +195,7 @@ QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) { switch (change) { case ItemPositionHasChanged: - foreach (Edge *edge, edgeList) + for (Edge *edge : qAsConst(edgeList)) edge->adjust(); graph->itemMoved(); break; diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp index 0c3ed86565..0c831360cf 100644 --- a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp @@ -60,7 +60,8 @@ EmbeddedDialog::EmbeddedDialog(QWidget *parent) ui->setupUi(this); ui->layoutDirection->setCurrentIndex(layoutDirection() != Qt::LeftToRight); - foreach (QString styleName, QStyleFactory::keys()) { + const QStringList styleKeys = QStyleFactory::keys(); + for (const QString &styleName : styleKeys) { ui->style->addItem(styleName); if (style()->objectName().toLower() == styleName.toLower()) ui->style->setCurrentIndex(ui->style->count() - 1); @@ -101,7 +102,8 @@ static void setStyleHelper(QWidget *widget, QStyle *style) { widget->setStyle(style); widget->setPalette(style->standardPalette()); - foreach (QObject *child, widget->children()) { + const QObjectList children = widget->children(); + for (QObject *child : children) { if (QWidget *childWidget = qobject_cast(child)) setStyleHelper(childWidget, style); } diff --git a/examples/widgets/graphicsview/flowlayout/flowlayout.cpp b/examples/widgets/graphicsview/flowlayout/flowlayout.cpp index 065c3e00ea..ab6bbb7aa4 100644 --- a/examples/widgets/graphicsview/flowlayout/flowlayout.cpp +++ b/examples/widgets/graphicsview/flowlayout/flowlayout.cpp @@ -154,8 +154,7 @@ QSizeF FlowLayout::minSize(const QSizeF &constraint) const } else if (constraint.height() >= 0) { // width for height? // not supported } else { - QGraphicsLayoutItem *item; - foreach (item, m_items) + for (const QGraphicsLayoutItem *item : qAsConst(m_items)) size = size.expandedTo(item->effectiveSizeHint(Qt::MinimumSize)); size += QSize(left + right, top + bottom); } @@ -167,10 +166,9 @@ QSizeF FlowLayout::prefSize() const qreal left, right; getContentsMargins(&left, 0, &right, 0); - QGraphicsLayoutItem *item; qreal maxh = 0; qreal totalWidth = 0; - foreach (item, m_items) { + for (const QGraphicsLayoutItem *item : qAsConst(m_items)) { if (totalWidth > 0) totalWidth += spacing(Qt::Horizontal); QSizeF pref = item->effectiveSizeHint(Qt::PreferredSize); @@ -187,10 +185,9 @@ QSizeF FlowLayout::prefSize() const QSizeF FlowLayout::maxSize() const { - QGraphicsLayoutItem *item; qreal totalWidth = 0; qreal totalHeight = 0; - foreach (item, m_items) { + for (const QGraphicsLayoutItem *item : qAsConst(m_items)) { if (totalWidth > 0) totalWidth += spacing(Qt::Horizontal); if (totalHeight > 0) -- cgit v1.2.3 From 34e4a8ef6d20e829a322bfef1d09136a37fecfd2 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 7 Dec 2018 12:01:42 +0100 Subject: Cleanup Widgets examples - foreach Cleanup the Widgets examples - replace foreach with range-based for loop in the remaining directories Change-Id: I321e6c0f414401a1ae4fb65762b97d894b725afa Reviewed-by: Paul Wicking Reviewed-by: Luca Beldi --- examples/widgets/animation/stickman/animation.cpp | 8 ++--- .../animation/sub-attaq/animationmanager.cpp | 4 +-- examples/widgets/animation/sub-attaq/bomb.cpp | 4 ++- .../widgets/animation/sub-attaq/graphicsscene.cpp | 6 ++-- examples/widgets/animation/sub-attaq/torpedo.cpp | 4 ++- examples/widgets/desktop/screenshot/screenshot.cpp | 3 +- .../widgets/dialogs/standarddialogs/dialog.cpp | 3 +- examples/widgets/doc/src/diagramscene.qdoc | 2 +- examples/widgets/doc/src/orderform.qdoc | 2 +- examples/widgets/doc/src/plugandpaint.qdoc | 4 +-- .../widgets/gestures/imagegestures/imagewidget.cpp | 2 +- examples/widgets/layouts/dynamiclayouts/dialog.cpp | 2 +- examples/widgets/layouts/flowlayout/flowlayout.cpp | 8 ++--- examples/widgets/richtext/orderform/mainwindow.cpp | 4 +-- .../richtext/syntaxhighlighter/highlighter.cpp | 39 +++++++++++----------- examples/widgets/richtext/textedit/textedit.cpp | 2 +- examples/widgets/scroller/graphicsview/main.cpp | 3 +- examples/widgets/statemachine/rogue/window.cpp | 3 +- 18 files changed, 54 insertions(+), 49 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/animation/stickman/animation.cpp b/examples/widgets/animation/stickman/animation.cpp index 94a92749bc..5c2d1682af 100644 --- a/examples/widgets/animation/stickman/animation.cpp +++ b/examples/widgets/animation/stickman/animation.cpp @@ -159,18 +159,16 @@ void Animation::save(QIODevice *device) const QDataStream stream(device); stream << m_name; stream << m_frames.size(); - foreach (Frame *frame, m_frames) { + for (const Frame *frame : qAsConst(m_frames)) { stream << frame->nodeCount(); - for (int i=0; inodeCount(); ++i) + for (int i = 0; i < frame->nodeCount(); ++i) stream << frame->nodePos(i); } } void Animation::load(QIODevice *device) { - if (!m_frames.isEmpty()) - qDeleteAll(m_frames); - + qDeleteAll(m_frames); m_frames.clear(); QDataStream stream(device); diff --git a/examples/widgets/animation/sub-attaq/animationmanager.cpp b/examples/widgets/animation/sub-attaq/animationmanager.cpp index e3dc27f37f..a611641613 100644 --- a/examples/widgets/animation/sub-attaq/animationmanager.cpp +++ b/examples/widgets/animation/sub-attaq/animationmanager.cpp @@ -93,14 +93,14 @@ void AnimationManager::unregisterAllAnimations() void AnimationManager::pauseAll() { - foreach (QAbstractAnimation* animation, animations) { + for (QAbstractAnimation *animation : qAsConst(animations)) { if (animation->state() == QAbstractAnimation::Running) animation->pause(); } } void AnimationManager::resumeAll() { - foreach (QAbstractAnimation* animation, animations) { + for (QAbstractAnimation *animation : qAsConst(animations)) { if (animation->state() == QAbstractAnimation::Paused) animation->resume(); } diff --git a/examples/widgets/animation/sub-attaq/bomb.cpp b/examples/widgets/animation/sub-attaq/bomb.cpp index 76e4575293..2b865137dd 100644 --- a/examples/widgets/animation/sub-attaq/bomb.cpp +++ b/examples/widgets/animation/sub-attaq/bomb.cpp @@ -112,7 +112,9 @@ void Bomb::launch(Bomb::Direction direction) void Bomb::onAnimationLaunchValueChanged(const QVariant &) { - foreach (QGraphicsItem * item , collidingItems(Qt::IntersectsItemBoundingRect)) { + const QList colItems = + collidingItems(Qt::IntersectsItemBoundingRect); + for (QGraphicsItem *item : colItems) { if (item->type() == SubMarine::Type) { SubMarine *s = static_cast(item); destroy(); diff --git a/examples/widgets/animation/sub-attaq/graphicsscene.cpp b/examples/widgets/animation/sub-attaq/graphicsscene.cpp index 3205cdc54d..8f0dfc1357 100644 --- a/examples/widgets/animation/sub-attaq/graphicsscene.cpp +++ b/examples/widgets/animation/sub-attaq/graphicsscene.cpp @@ -265,17 +265,17 @@ void GraphicsScene::onSubMarineExecutionFinished() void GraphicsScene::clearScene() { - foreach (SubMarine *sub, submarines) { + for (SubMarine *sub : qAsConst(submarines)) { sub->destroy(); sub->deleteLater(); } - foreach (Torpedo *torpedo, torpedos) { + for (Torpedo *torpedo : qAsConst(torpedos)) { torpedo->destroy(); torpedo->deleteLater(); } - foreach (Bomb *bomb, bombs) { + for (Bomb *bomb : qAsConst(bombs)) { bomb->destroy(); bomb->deleteLater(); } diff --git a/examples/widgets/animation/sub-attaq/torpedo.cpp b/examples/widgets/animation/sub-attaq/torpedo.cpp index 5f8ef2f2b8..92a3833452 100644 --- a/examples/widgets/animation/sub-attaq/torpedo.cpp +++ b/examples/widgets/animation/sub-attaq/torpedo.cpp @@ -111,7 +111,9 @@ void Torpedo::setCurrentSpeed(int speed) void Torpedo::onAnimationLaunchValueChanged(const QVariant &) { - foreach (QGraphicsItem *item , collidingItems(Qt::IntersectsItemBoundingRect)) { + const QList colItems = + collidingItems(Qt::IntersectsItemBoundingRect); + for (QGraphicsItem *item : colItems) { if (Boat *b = qgraphicsitem_cast(item)) b->destroy(); } diff --git a/examples/widgets/desktop/screenshot/screenshot.cpp b/examples/widgets/desktop/screenshot/screenshot.cpp index 80f26ae282..715e6c780e 100644 --- a/examples/widgets/desktop/screenshot/screenshot.cpp +++ b/examples/widgets/desktop/screenshot/screenshot.cpp @@ -139,7 +139,8 @@ void Screenshot::saveScreenshot() fileDialog.setFileMode(QFileDialog::AnyFile); fileDialog.setDirectory(initialPath); QStringList mimeTypes; - foreach (const QByteArray &bf, QImageWriter::supportedMimeTypes()) + const QList baMimeTypes = QImageWriter::supportedMimeTypes(); + for (const QByteArray &bf : baMimeTypes) mimeTypes.append(QLatin1String(bf)); fileDialog.setMimeTypeFilters(mimeTypes); fileDialog.selectMimeTypeFilter("image/" + format); diff --git a/examples/widgets/dialogs/standarddialogs/dialog.cpp b/examples/widgets/dialogs/standarddialogs/dialog.cpp index 4b59aab887..1830b21e8f 100644 --- a/examples/widgets/dialogs/standarddialogs/dialog.cpp +++ b/examples/widgets/dialogs/standarddialogs/dialog.cpp @@ -99,9 +99,10 @@ void DialogOptionsWidget::addSpacer() int DialogOptionsWidget::value() const { int result = 0; - foreach (const CheckBoxEntry &checkboxEntry, checkBoxEntries) + for (const CheckBoxEntry &checkboxEntry : qAsConst(checkBoxEntries)) { if (checkboxEntry.first->isChecked()) result |= checkboxEntry.second; + } return result; } diff --git a/examples/widgets/doc/src/diagramscene.qdoc b/examples/widgets/doc/src/diagramscene.qdoc index ca4876f2e8..860dcc5cb9 100644 --- a/examples/widgets/doc/src/diagramscene.qdoc +++ b/examples/widgets/doc/src/diagramscene.qdoc @@ -589,7 +589,7 @@ \snippet graphicsview/diagramscene/diagramscene.cpp 14 The scene has single selection, i.e., only one item can be - selected at any given time. The foreach will then loop one time + selected at any given time. The for loop will then loop one time with the selected item or none if no item is selected. \c isItemChange() is used to check whether a selected item exists and also is of the specified diagram \a type. diff --git a/examples/widgets/doc/src/orderform.qdoc b/examples/widgets/doc/src/orderform.qdoc index de59fc402d..5c63081a77 100644 --- a/examples/widgets/doc/src/orderform.qdoc +++ b/examples/widgets/doc/src/orderform.qdoc @@ -191,7 +191,7 @@ We then set the \c{cursor}'s position back to its last position in \c topFrame and fill in the customer's name (provided by the constructor) - and address - using a \c foreach loop to traverse the QString, \c address. + and address - using a range-based for loop to traverse the QString, \c address. \snippet richtext/orderform/mainwindow.cpp 4 diff --git a/examples/widgets/doc/src/plugandpaint.qdoc b/examples/widgets/doc/src/plugandpaint.qdoc index d3044860ab..b37176da0e 100644 --- a/examples/widgets/doc/src/plugandpaint.qdoc +++ b/examples/widgets/doc/src/plugandpaint.qdoc @@ -171,8 +171,8 @@ \snippet tools/plugandpaint/app/mainwindow.cpp 8 We use QDir::entryList() to get a list of all files in that - directory. Then we iterate over the result using \l foreach and - try to load the plugin using QPluginLoader. + directory. Then we iterate over the result using a range-based for loop + and try to load the plugin using QPluginLoader. The QObject provided by the plugin is accessible through QPluginLoader::instance(). If the dynamic library isn't a Qt diff --git a/examples/widgets/gestures/imagegestures/imagewidget.cpp b/examples/widgets/gestures/imagegestures/imagewidget.cpp index ca9affca70..0a6b963559 100644 --- a/examples/widgets/gestures/imagegestures/imagewidget.cpp +++ b/examples/widgets/gestures/imagegestures/imagewidget.cpp @@ -72,7 +72,7 @@ ImageWidget::ImageWidget(QWidget *parent) void ImageWidget::grabGestures(const QList &gestures) { //! [enable gestures] - foreach (Qt::GestureType gesture, gestures) + for (Qt::GestureType gesture : gestures) grabGesture(gesture); //! [enable gestures] } diff --git a/examples/widgets/layouts/dynamiclayouts/dialog.cpp b/examples/widgets/layouts/dynamiclayouts/dialog.cpp index f46053372a..baf3b4cf1e 100644 --- a/examples/widgets/layouts/dynamiclayouts/dialog.cpp +++ b/examples/widgets/layouts/dynamiclayouts/dialog.cpp @@ -104,7 +104,7 @@ void Dialog::rotateWidgets() { Q_ASSERT(rotatableWidgets.count() % 2 == 0); - foreach (QWidget *widget, rotatableWidgets) + for (QWidget *widget : qAsConst(rotatableWidgets)) rotatableLayout->removeWidget(widget); rotatableWidgets.enqueue(rotatableWidgets.dequeue()); diff --git a/examples/widgets/layouts/flowlayout/flowlayout.cpp b/examples/widgets/layouts/flowlayout/flowlayout.cpp index b7064d98b1..53613b8b20 100644 --- a/examples/widgets/layouts/flowlayout/flowlayout.cpp +++ b/examples/widgets/layouts/flowlayout/flowlayout.cpp @@ -155,8 +155,7 @@ QSize FlowLayout::sizeHint() const QSize FlowLayout::minimumSize() const { QSize size; - QLayoutItem *item; - foreach (item, itemList) + for (const QLayoutItem *item : qAsConst(itemList)) size = size.expandedTo(item->minimumSize()); size += QSize(2*margin(), 2*margin()); @@ -176,9 +175,8 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const //! [9] //! [10] - QLayoutItem *item; - foreach (item, itemList) { - QWidget *wid = item->widget(); + for (QLayoutItem *item : qAsConst(itemList)) { + const QWidget *wid = item->widget(); int spaceX = horizontalSpacing(); if (spaceX == -1) spaceX = wid->style()->layoutSpacing( diff --git a/examples/widgets/richtext/orderform/mainwindow.cpp b/examples/widgets/richtext/orderform/mainwindow.cpp index 291c37edf6..0b6a2cac6c 100644 --- a/examples/widgets/richtext/orderform/mainwindow.cpp +++ b/examples/widgets/richtext/orderform/mainwindow.cpp @@ -126,8 +126,8 @@ void MainWindow::createLetter(const QString &name, const QString &address, cursor.setPosition(topFrame->lastPosition()); cursor.insertText(name, textFormat); - QString line; - foreach (line, address.split("\n")) { + const QStringList lines = address.split('\n'); + for (const QString &line : lines) { cursor.insertBlock(); cursor.insertText(line); } diff --git a/examples/widgets/richtext/syntaxhighlighter/highlighter.cpp b/examples/widgets/richtext/syntaxhighlighter/highlighter.cpp index 6c420c328a..0c10eed6cf 100644 --- a/examples/widgets/richtext/syntaxhighlighter/highlighter.cpp +++ b/examples/widgets/richtext/syntaxhighlighter/highlighter.cpp @@ -58,18 +58,19 @@ Highlighter::Highlighter(QTextDocument *parent) keywordFormat.setForeground(Qt::darkBlue); keywordFormat.setFontWeight(QFont::Bold); - QStringList keywordPatterns; - keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b" - << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b" - << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b" - << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b" - << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b" - << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b" - << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b" - << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b" - << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b" - << "\\bvoid\\b" << "\\bvolatile\\b" << "\\bbool\\b"; - foreach (const QString &pattern, keywordPatterns) { + const QString keywordPatterns[] = { + QStringLiteral("\\bchar\\b"), QStringLiteral("\\bclass\\b"), QStringLiteral("\\bconst\\b"), + QStringLiteral("\\bdouble\\b"), QStringLiteral("\\benum\\b"), QStringLiteral("\\bexplicit\\b"), + QStringLiteral("\\bfriend\\b"), QStringLiteral("\\binline\\b"), QStringLiteral("\\bint\\b"), + QStringLiteral("\\blong\\b"), QStringLiteral("\\bnamespace\\b"), QStringLiteral("\\boperator\\b"), + QStringLiteral("\\bprivate\\b"), QStringLiteral("\\bprotected\\b"), QStringLiteral("\\bpublic\\b"), + QStringLiteral("\\bshort\\b"), QStringLiteral("\\bsignals\\b"), QStringLiteral("\\bsigned\\b"), + QStringLiteral("\\bslots\\b"), QStringLiteral("\\bstatic\\b"), QStringLiteral("\\bstruct\\b"), + QStringLiteral("\\btemplate\\b"), QStringLiteral("\\btypedef\\b"), QStringLiteral("\\btypename\\b"), + QStringLiteral("\\bunion\\b"), QStringLiteral("\\bunsigned\\b"), QStringLiteral("\\bvirtual\\b"), + QStringLiteral("\\bvoid\\b"), QStringLiteral("\\bvolatile\\b"), QStringLiteral("\\bbool\\b") + }; + for (const QString &pattern : keywordPatterns) { rule.pattern = QRegularExpression(pattern); rule.format = keywordFormat; highlightingRules.append(rule); @@ -80,14 +81,14 @@ Highlighter::Highlighter(QTextDocument *parent) //! [2] classFormat.setFontWeight(QFont::Bold); classFormat.setForeground(Qt::darkMagenta); - rule.pattern = QRegularExpression("\\bQ[A-Za-z]+\\b"); + rule.pattern = QRegularExpression(QStringLiteral("\\bQ[A-Za-z]+\\b")); rule.format = classFormat; highlightingRules.append(rule); //! [2] //! [3] singleLineCommentFormat.setForeground(Qt::red); - rule.pattern = QRegularExpression("//[^\n]*"); + rule.pattern = QRegularExpression(QStringLiteral("//[^\n]*")); rule.format = singleLineCommentFormat; highlightingRules.append(rule); @@ -96,7 +97,7 @@ Highlighter::Highlighter(QTextDocument *parent) //! [4] quotationFormat.setForeground(Qt::darkGreen); - rule.pattern = QRegularExpression("\".*\""); + rule.pattern = QRegularExpression(QStringLiteral("\".*\"")); rule.format = quotationFormat; highlightingRules.append(rule); //! [4] @@ -104,21 +105,21 @@ Highlighter::Highlighter(QTextDocument *parent) //! [5] functionFormat.setFontItalic(true); functionFormat.setForeground(Qt::blue); - rule.pattern = QRegularExpression("\\b[A-Za-z0-9_]+(?=\\()"); + rule.pattern = QRegularExpression(QStringLiteral("\\b[A-Za-z0-9_]+(?=\\()")); rule.format = functionFormat; highlightingRules.append(rule); //! [5] //! [6] - commentStartExpression = QRegularExpression("/\\*"); - commentEndExpression = QRegularExpression("\\*/"); + commentStartExpression = QRegularExpression(QStringLiteral("/\\*")); + commentEndExpression = QRegularExpression(QStringLiteral("\\*/")); } //! [6] //! [7] void Highlighter::highlightBlock(const QString &text) { - foreach (const HighlightingRule &rule, highlightingRules) { + for (const HighlightingRule &rule : qAsConst(highlightingRules)) { QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); while (matchIterator.hasNext()) { QRegularExpressionMatch match = matchIterator.next(); diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp index 0d51ce61ad..00ea0325dc 100644 --- a/examples/widgets/richtext/textedit/textedit.cpp +++ b/examples/widgets/richtext/textedit/textedit.cpp @@ -377,7 +377,7 @@ void TextEdit::setupTextActions() comboSize->setEditable(true); const QList standardSizes = QFontDatabase::standardSizes(); - foreach (int size, standardSizes) + for (int size : standardSizes) comboSize->addItem(QString::number(size)); comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); diff --git a/examples/widgets/scroller/graphicsview/main.cpp b/examples/widgets/scroller/graphicsview/main.cpp index c33a3091ed..d6b2956d50 100644 --- a/examples/widgets/scroller/graphicsview/main.cpp +++ b/examples/widgets/scroller/graphicsview/main.cpp @@ -117,7 +117,8 @@ public: QRectF boundingRect() const override { QRectF rect; - foreach (QGraphicsItem *item, childItems()) + const auto items = childItems(); + for (const QGraphicsItem *item : items) rect |= item->boundingRect().translated(item->pos()); return rect; } diff --git a/examples/widgets/statemachine/rogue/window.cpp b/examples/widgets/statemachine/rogue/window.cpp index f91a6e522e..a5363e2758 100644 --- a/examples/widgets/statemachine/rogue/window.cpp +++ b/examples/widgets/statemachine/rogue/window.cpp @@ -66,7 +66,8 @@ Window::Window() font = QFont("Monospace"); } else { - foreach (QString family, database.families()) { + const QStringList fontFamilies = database.families(); + for (const QString &family : fontFamilies ) { if (database.isFixedPitch(family)) { font = QFont(family); break; -- cgit v1.2.3 From e0e22d56ac4a37a57d02383747fbacccaaa407bd Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 23 Nov 2018 19:45:56 +0100 Subject: Cleanup EditableItemModel example Cleanup the EditableItemModel example: - include own headers first - use nullptr - add sanity checks - use for loop instead foreach - use const where possible Change-Id: Ib36e5710c07979576b48a905ee50908a64dcb697 Reviewed-by: Paul Wicking --- .../widgets/itemviews/editabletreemodel/main.cpp | 4 +- .../itemviews/editabletreemodel/mainwindow.cpp | 32 +++++------ .../itemviews/editabletreemodel/mainwindow.h | 3 +- .../itemviews/editabletreemodel/treeitem.cpp | 22 ++++---- .../widgets/itemviews/editabletreemodel/treeitem.h | 5 +- .../itemviews/editabletreemodel/treemodel.cpp | 66 +++++++++++----------- .../itemviews/editabletreemodel/treemodel.h | 2 +- 7 files changed, 66 insertions(+), 68 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/itemviews/editabletreemodel/main.cpp b/examples/widgets/itemviews/editabletreemodel/main.cpp index 80f6842730..5e9ff214a3 100644 --- a/examples/widgets/itemviews/editabletreemodel/main.cpp +++ b/examples/widgets/itemviews/editabletreemodel/main.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "mainwindow.h" +#include + int main(int argc, char *argv[]) { Q_INIT_RESOURCE(editabletreemodel); diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp b/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp index 0c54d8930f..7faa325469 100644 --- a/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp +++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp @@ -58,8 +58,7 @@ MainWindow::MainWindow(QWidget *parent) { setupUi(this); - QStringList headers; - headers << tr("Title") << tr("Description"); + const QStringList headers({tr("Title"), tr("Description")}); QFile file(":/default.txt"); file.open(QIODevice::ReadOnly); @@ -87,7 +86,7 @@ MainWindow::MainWindow(QWidget *parent) void MainWindow::insertChild() { - QModelIndex index = view->selectionModel()->currentIndex(); + const QModelIndex index = view->selectionModel()->currentIndex(); QAbstractItemModel *model = view->model(); if (model->columnCount(index) == 0) { @@ -99,10 +98,10 @@ void MainWindow::insertChild() return; for (int column = 0; column < model->columnCount(index); ++column) { - QModelIndex child = model->index(0, column, index); - model->setData(child, QVariant("[No data]"), Qt::EditRole); + const QModelIndex child = model->index(0, column, index); + model->setData(child, QVariant(tr("[No data]")), Qt::EditRole); if (!model->headerData(column, Qt::Horizontal).isValid()) - model->setHeaderData(column, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole); + model->setHeaderData(column, Qt::Horizontal, QVariant(tr("[No header]")), Qt::EditRole); } view->selectionModel()->setCurrentIndex(model->index(0, 0, index), @@ -127,7 +126,7 @@ bool MainWindow::insertColumn() void MainWindow::insertRow() { - QModelIndex index = view->selectionModel()->currentIndex(); + const QModelIndex index = view->selectionModel()->currentIndex(); QAbstractItemModel *model = view->model(); if (!model->insertRow(index.row()+1, index.parent())) @@ -136,19 +135,18 @@ void MainWindow::insertRow() updateActions(); for (int column = 0; column < model->columnCount(index.parent()); ++column) { - QModelIndex child = model->index(index.row()+1, column, index.parent()); - model->setData(child, QVariant("[No data]"), Qt::EditRole); + const QModelIndex child = model->index(index.row() + 1, column, index.parent()); + model->setData(child, QVariant(tr("[No data]")), Qt::EditRole); } } bool MainWindow::removeColumn() { QAbstractItemModel *model = view->model(); - int column = view->selectionModel()->currentIndex().column(); + const int column = view->selectionModel()->currentIndex().column(); // Insert columns in each child of the parent item. - bool changed = model->removeColumn(column); - + const bool changed = model->removeColumn(column); if (changed) updateActions(); @@ -157,7 +155,7 @@ bool MainWindow::removeColumn() void MainWindow::removeRow() { - QModelIndex index = view->selectionModel()->currentIndex(); + const QModelIndex index = view->selectionModel()->currentIndex(); QAbstractItemModel *model = view->model(); if (model->removeRow(index.row(), index.parent())) updateActions(); @@ -165,19 +163,19 @@ void MainWindow::removeRow() void MainWindow::updateActions() { - bool hasSelection = !view->selectionModel()->selection().isEmpty(); + const bool hasSelection = !view->selectionModel()->selection().isEmpty(); removeRowAction->setEnabled(hasSelection); removeColumnAction->setEnabled(hasSelection); - bool hasCurrent = view->selectionModel()->currentIndex().isValid(); + const bool hasCurrent = view->selectionModel()->currentIndex().isValid(); insertRowAction->setEnabled(hasCurrent); insertColumnAction->setEnabled(hasCurrent); if (hasCurrent) { view->closePersistentEditor(view->selectionModel()->currentIndex()); - int row = view->selectionModel()->currentIndex().row(); - int column = view->selectionModel()->currentIndex().column(); + const int row = view->selectionModel()->currentIndex().row(); + const int column = view->selectionModel()->currentIndex().column(); if (view->selectionModel()->currentIndex().parent().isValid()) statusBar()->showMessage(tr("Position: (%1,%2)").arg(row).arg(column)); else diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.h b/examples/widgets/itemviews/editabletreemodel/mainwindow.h index dbc745e25d..314b0cb1fa 100644 --- a/examples/widgets/itemviews/editabletreemodel/mainwindow.h +++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.h @@ -54,14 +54,13 @@ #include "ui_mainwindow.h" #include -#include class MainWindow : public QMainWindow, private Ui::MainWindow { Q_OBJECT public: - MainWindow(QWidget *parent = 0); + MainWindow(QWidget *parent = nullptr); public slots: void updateActions(); diff --git a/examples/widgets/itemviews/editabletreemodel/treeitem.cpp b/examples/widgets/itemviews/editabletreemodel/treeitem.cpp index 8fbe86ad1e..027a5f8849 100644 --- a/examples/widgets/itemviews/editabletreemodel/treeitem.cpp +++ b/examples/widgets/itemviews/editabletreemodel/treeitem.cpp @@ -56,14 +56,11 @@ #include "treeitem.h" -#include - //! [0] TreeItem::TreeItem(const QVector &data, TreeItem *parent) -{ - parentItem = parent; - itemData = data; -} + : itemData(data), + parentItem(parent) +{} //! [0] //! [1] @@ -76,7 +73,9 @@ TreeItem::~TreeItem() //! [2] TreeItem *TreeItem::child(int number) { - return childItems.value(number); + if (number < 0 || number >= childItems.size()) + return nullptr; + return childItems.at(number); } //! [2] @@ -92,7 +91,6 @@ int TreeItem::childNumber() const { if (parentItem) return parentItem->childItems.indexOf(const_cast(this)); - return 0; } //! [4] @@ -107,7 +105,9 @@ int TreeItem::columnCount() const //! [6] QVariant TreeItem::data(int column) const { - return itemData.value(column); + if (column < 0 || column >= itemData.size()) + return QVariant(); + return itemData.at(column); } //! [6] @@ -136,7 +136,7 @@ bool TreeItem::insertColumns(int position, int columns) for (int column = 0; column < columns; ++column) itemData.insert(position, QVariant()); - foreach (TreeItem *child, childItems) + for (TreeItem *child : qAsConst(childItems)) child->insertColumns(position, columns); return true; @@ -171,7 +171,7 @@ bool TreeItem::removeColumns(int position, int columns) for (int column = 0; column < columns; ++column) itemData.remove(position); - foreach (TreeItem *child, childItems) + for (TreeItem *child : qAsConst(childItems)) child->removeColumns(position, columns); return true; diff --git a/examples/widgets/itemviews/editabletreemodel/treeitem.h b/examples/widgets/itemviews/editabletreemodel/treeitem.h index fd65f12268..867be5f380 100644 --- a/examples/widgets/itemviews/editabletreemodel/treeitem.h +++ b/examples/widgets/itemviews/editabletreemodel/treeitem.h @@ -51,7 +51,6 @@ #ifndef TREEITEM_H #define TREEITEM_H -#include #include #include @@ -59,7 +58,7 @@ class TreeItem { public: - explicit TreeItem(const QVector &data, TreeItem *parent = 0); + explicit TreeItem(const QVector &data, TreeItem *parent = nullptr); ~TreeItem(); TreeItem *child(int number); @@ -75,7 +74,7 @@ public: bool setData(int column, const QVariant &value); private: - QList childItems; + QVector childItems; QVector itemData; TreeItem *parentItem; }; diff --git a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp index 72818372d7..836c2e8651 100644 --- a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp +++ b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp @@ -48,21 +48,21 @@ ** ****************************************************************************/ -#include - -#include "treeitem.h" #include "treemodel.h" +#include "treeitem.h" + +#include //! [0] TreeModel::TreeModel(const QStringList &headers, const QString &data, QObject *parent) : QAbstractItemModel(parent) { QVector rootData; - foreach (QString header, headers) + for (const QString &header : headers) rootData << header; rootItem = new TreeItem(rootData); - setupModelData(data.split(QString("\n")), rootItem); + setupModelData(data.split('\n'), rootItem); } //! [0] @@ -74,8 +74,9 @@ TreeModel::~TreeModel() //! [1] //! [2] -int TreeModel::columnCount(const QModelIndex & /* parent */) const +int TreeModel::columnCount(const QModelIndex &parent) const { + Q_UNUSED(parent); return rootItem->columnCount(); } //! [2] @@ -97,7 +98,7 @@ QVariant TreeModel::data(const QModelIndex &index, int role) const Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const { if (!index.isValid()) - return 0; + return Qt::NoItemFlags; return Qt::ItemIsEditable | QAbstractItemModel::flags(index); } @@ -133,21 +134,20 @@ QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) con //! [6] TreeItem *parentItem = getItem(parent); + if (!parentItem) + return QModelIndex(); TreeItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); - else - return QModelIndex(); + return QModelIndex(); } //! [6] bool TreeModel::insertColumns(int position, int columns, const QModelIndex &parent) { - bool success; - beginInsertColumns(parent, position, position + columns - 1); - success = rootItem->insertColumns(position, columns); + const bool success = rootItem->insertColumns(position, columns); endInsertColumns(); return success; @@ -156,10 +156,13 @@ bool TreeModel::insertColumns(int position, int columns, const QModelIndex &pare bool TreeModel::insertRows(int position, int rows, const QModelIndex &parent) { TreeItem *parentItem = getItem(parent); - bool success; + if (!parentItem) + return false; beginInsertRows(parent, position, position + rows - 1); - success = parentItem->insertChildren(position, rows, rootItem->columnCount()); + const bool success = parentItem->insertChildren(position, + rows, + rootItem->columnCount()); endInsertRows(); return success; @@ -172,9 +175,9 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const return QModelIndex(); TreeItem *childItem = getItem(index); - TreeItem *parentItem = childItem->parent(); + TreeItem *parentItem = childItem ? childItem->parent() : nullptr; - if (parentItem == rootItem) + if (parentItem == rootItem || !parentItem) return QModelIndex(); return createIndex(parentItem->childNumber(), 0, parentItem); @@ -183,10 +186,8 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const bool TreeModel::removeColumns(int position, int columns, const QModelIndex &parent) { - bool success; - beginRemoveColumns(parent, position, position + columns - 1); - success = rootItem->removeColumns(position, columns); + const bool success = rootItem->removeColumns(position, columns); endRemoveColumns(); if (rootItem->columnCount() == 0) @@ -198,10 +199,11 @@ bool TreeModel::removeColumns(int position, int columns, const QModelIndex &pare bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent) { TreeItem *parentItem = getItem(parent); - bool success = true; + if (!parentItem) + return false; beginRemoveRows(parent, position, position + rows - 1); - success = parentItem->removeChildren(position, rows); + const bool success = parentItem->removeChildren(position, rows); endRemoveRows(); return success; @@ -210,9 +212,9 @@ bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent) //! [8] int TreeModel::rowCount(const QModelIndex &parent) const { - TreeItem *parentItem = getItem(parent); + const TreeItem *parentItem = getItem(parent); - return parentItem->childCount(); + return parentItem ? parentItem->childCount() : 0; } //! [8] @@ -225,7 +227,7 @@ bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int rol bool result = item->setData(index.column(), value); if (result) - emit dataChanged(index, index, {role}); + emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole}); return result; } @@ -236,7 +238,7 @@ bool TreeModel::setHeaderData(int section, Qt::Orientation orientation, if (role != Qt::EditRole || orientation != Qt::Horizontal) return false; - bool result = rootItem->setData(section, value); + const bool result = rootItem->setData(section, value); if (result) emit headerDataChanged(orientation, section, section); @@ -246,8 +248,8 @@ bool TreeModel::setHeaderData(int section, Qt::Orientation orientation, void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) { - QList parents; - QList indentations; + QVector parents; + QVector indentations; parents << parent; indentations << 0; @@ -261,14 +263,15 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) ++position; } - QString lineData = lines[number].mid(position).trimmed(); + const QString lineData = lines[number].mid(position).trimmed(); if (!lineData.isEmpty()) { // Read the column data from the rest of the line. - QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); + const QStringList columnStrings = lineData.split('\t', QString::SkipEmptyParts); QVector columnData; - for (int column = 0; column < columnStrings.count(); ++column) - columnData << columnStrings[column]; + columnData.reserve(columnStrings.size()); + for (const QString &columnString : columnStrings) + columnData << columnString; if (position > indentations.last()) { // The last child of the current parent is now the new parent @@ -291,7 +294,6 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) for (int column = 0; column < columnData.size(); ++column) parent->child(parent->childCount() - 1)->setData(column, columnData[column]); } - ++number; } } diff --git a/examples/widgets/itemviews/editabletreemodel/treemodel.h b/examples/widgets/itemviews/editabletreemodel/treemodel.h index d76d138831..8419f9cb9d 100644 --- a/examples/widgets/itemviews/editabletreemodel/treemodel.h +++ b/examples/widgets/itemviews/editabletreemodel/treemodel.h @@ -64,7 +64,7 @@ class TreeModel : public QAbstractItemModel public: TreeModel(const QStringList &headers, const QString &data, - QObject *parent = 0); + QObject *parent = nullptr); ~TreeModel(); //! [0] //! [1] -- cgit v1.2.3 From bf4bf3a58360d4f7907895096b452cb3821ea593 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 2 Dec 2018 14:16:47 +0100 Subject: Cleanup Widgets examples - signals/slots Cleanup the widgets examples - use new signal/slot syntax where possible Change-Id: I6bc8953534d8b1efca0de4ee6a9fe4a6aa79fda9 Reviewed-by: Samuel Gaist Reviewed-by: Konstantin Shegunov Reviewed-by: Edward Welbourne Reviewed-by: Paul Wicking --- .../widgets/widgets/analogclock/analogclock.cpp | 2 +- examples/widgets/widgets/calendarwidget/window.cpp | 76 +++++++++++----------- examples/widgets/widgets/codeeditor/codeeditor.cpp | 6 +- examples/widgets/widgets/lineedits/window.cpp | 20 +++--- examples/widgets/widgets/mousebuttons/main.cpp | 2 +- examples/widgets/widgets/movie/movieplayer.cpp | 23 ++++--- examples/widgets/widgets/scribble/mainwindow.cpp | 20 +++--- .../widgets/widgets/shapedclock/shapedclock.cpp | 4 +- examples/widgets/widgets/sliders/slidersgroup.cpp | 8 +-- examples/widgets/widgets/sliders/window.cpp | 48 +++++++------- examples/widgets/widgets/spinboxes/window.cpp | 8 +-- examples/widgets/widgets/styles/widgetgallery.cpp | 26 ++++---- examples/widgets/widgets/stylesheet/mainwindow.cpp | 4 +- examples/widgets/widgets/validators/ledwidget.cpp | 2 +- .../widgets/widgets/validators/localeselector.cpp | 3 +- .../widgets/windowflags/controllerwindow.cpp | 9 ++- .../widgets/widgets/windowflags/previewwindow.cpp | 3 +- 17 files changed, 134 insertions(+), 130 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/analogclock/analogclock.cpp b/examples/widgets/widgets/analogclock/analogclock.cpp index 0dc2fbc708..bee316b9b7 100644 --- a/examples/widgets/widgets/analogclock/analogclock.cpp +++ b/examples/widgets/widgets/analogclock/analogclock.cpp @@ -61,7 +61,7 @@ AnalogClock::AnalogClock(QWidget *parent) //! [3] //! [4] QTimer *timer = new QTimer(this); //! [4] //! [5] - connect(timer, SIGNAL(timeout()), this, SLOT(update())); + connect(timer, &QTimer::timeout, this, QOverload<>::of(&AnalogClock::update)); //! [5] //! [6] timer->start(1000); //! [6] diff --git a/examples/widgets/widgets/calendarwidget/window.cpp b/examples/widgets/widgets/calendarwidget/window.cpp index a1c1746786..64047aaac9 100644 --- a/examples/widgets/widgets/calendarwidget/window.cpp +++ b/examples/widgets/widgets/calendarwidget/window.cpp @@ -221,8 +221,8 @@ void Window::createPreviewGroupBox() calendar->setMaximumDate(QDate(3000, 1, 1)); calendar->setGridVisible(true); - connect(calendar, SIGNAL(currentPageChanged(int,int)), - this, SLOT(reformatCalendarPage())); + connect(calendar, &QCalendarWidget::currentPageChanged, + this, &Window::reformatCalendarPage); previewLayout = new QGridLayout; previewLayout->addWidget(calendar, 0, 0, Qt::AlignCenter); @@ -306,20 +306,20 @@ void Window::createGeneralOptionsGroupBox() verticalHeaderLabel->setBuddy(verticalHeaderCombo); //! [11] - connect(localeCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(localeChanged(int))); - connect(firstDayCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(firstDayChanged(int))); - connect(selectionModeCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(selectionModeChanged(int))); - connect(gridCheckBox, SIGNAL(toggled(bool)), - calendar, SLOT(setGridVisible(bool))); - connect(navigationCheckBox, SIGNAL(toggled(bool)), - calendar, SLOT(setNavigationBarVisible(bool))); - connect(horizontalHeaderCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(horizontalHeaderChanged(int))); - connect(verticalHeaderCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(verticalHeaderChanged(int))); + connect(localeCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::localeChanged); + connect(firstDayCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::firstDayChanged); + connect(selectionModeCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::selectionModeChanged); + connect(gridCheckBox, &QCheckBox::toggled, + calendar, &QCalendarWidget::setGridVisible); + connect(navigationCheckBox, &QCheckBox::toggled, + calendar, &QCalendarWidget::setNavigationBarVisible); + connect(horizontalHeaderCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::horizontalHeaderChanged); + connect(verticalHeaderCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::verticalHeaderChanged); //! [11] QHBoxLayout *checkBoxLayout = new QHBoxLayout; @@ -382,14 +382,14 @@ void Window::createDatesGroupBox() maximumDateLabel->setBuddy(maximumDateEdit); //! [13] //! [14] - connect(currentDateEdit, SIGNAL(dateChanged(QDate)), - calendar, SLOT(setSelectedDate(QDate))); - connect(calendar, SIGNAL(selectionChanged()), - this, SLOT(selectedDateChanged())); - connect(minimumDateEdit, SIGNAL(dateChanged(QDate)), - this, SLOT(minimumDateChanged(QDate))); - connect(maximumDateEdit, SIGNAL(dateChanged(QDate)), - this, SLOT(maximumDateChanged(QDate))); + connect(currentDateEdit, &QDateEdit::dateChanged, + calendar, &QCalendarWidget::setSelectedDate); + connect(calendar, &QCalendarWidget::selectionChanged, + this, &Window::selectedDateChanged); + connect(minimumDateEdit, &QDateEdit::dateChanged, + this, &Window::minimumDateChanged); + connect(maximumDateEdit, &QDateEdit::dateChanged, + this, &Window::maximumDateChanged); //! [14] QGridLayout *dateBoxLayout = new QGridLayout; @@ -439,20 +439,20 @@ void Window::createTextFormatsGroupBox() mayFirstCheckBox = new QCheckBox(tr("May &1 in red")); //! [17] //! [18] - connect(weekdayColorCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(weekdayFormatChanged())); - connect(weekdayColorCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(reformatCalendarPage())); - connect(weekendColorCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(weekendFormatChanged())); - connect(weekendColorCombo, SIGNAL(currentIndexChanged(int)), - this, SLOT(reformatCalendarPage())); - connect(headerTextFormatCombo, SIGNAL(currentIndexChanged(QString)), - this, SLOT(reformatHeaders())); - connect(firstFridayCheckBox, SIGNAL(toggled(bool)), - this, SLOT(reformatCalendarPage())); - connect(mayFirstCheckBox, SIGNAL(toggled(bool)), - this, SLOT(reformatCalendarPage())); + connect(weekdayColorCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::weekdayFormatChanged); + connect(weekdayColorCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::reformatCalendarPage); + connect(weekendColorCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::weekendFormatChanged); + connect(weekendColorCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::reformatCalendarPage); + connect(headerTextFormatCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &Window::reformatHeaders); + connect(firstFridayCheckBox, &QCheckBox::toggled, + this, &Window::reformatCalendarPage); + connect(mayFirstCheckBox, &QCheckBox::toggled, + this, &Window::reformatCalendarPage); //! [18] QHBoxLayout *checkBoxLayout = new QHBoxLayout; diff --git a/examples/widgets/widgets/codeeditor/codeeditor.cpp b/examples/widgets/widgets/codeeditor/codeeditor.cpp index 7e56a75294..8e29860669 100644 --- a/examples/widgets/widgets/codeeditor/codeeditor.cpp +++ b/examples/widgets/widgets/codeeditor/codeeditor.cpp @@ -58,9 +58,9 @@ CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent) { lineNumberArea = new LineNumberArea(this); - connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); - connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); - connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); + connect(this, &CodeEditor::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth); + connect(this, &CodeEditor::updateRequest, this, &CodeEditor::updateLineNumberArea); + connect(this, &CodeEditor::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine); updateLineNumberAreaWidth(0); highlightCurrentLine(); diff --git a/examples/widgets/widgets/lineedits/window.cpp b/examples/widgets/widgets/lineedits/window.cpp index 0926f6f20b..33f09d544d 100644 --- a/examples/widgets/widgets/lineedits/window.cpp +++ b/examples/widgets/widgets/lineedits/window.cpp @@ -123,16 +123,16 @@ Window::Window(QWidget *parent) //! [4] //! [5] - connect(echoComboBox, SIGNAL(activated(int)), - this, SLOT(echoChanged(int))); - connect(validatorComboBox, SIGNAL(activated(int)), - this, SLOT(validatorChanged(int))); - connect(alignmentComboBox, SIGNAL(activated(int)), - this, SLOT(alignmentChanged(int))); - connect(inputMaskComboBox, SIGNAL(activated(int)), - this, SLOT(inputMaskChanged(int))); - connect(accessComboBox, SIGNAL(activated(int)), - this, SLOT(accessChanged(int))); + connect(echoComboBox, QOverload::of(&QComboBox::activated), + this, &Window::echoChanged); + connect(validatorComboBox, QOverload::of(&QComboBox::activated), + this, &Window::validatorChanged); + connect(alignmentComboBox, QOverload::of(&QComboBox::activated), + this, &Window::alignmentChanged); + connect(inputMaskComboBox, QOverload::of(&QComboBox::activated), + this, &Window::inputMaskChanged); + connect(accessComboBox, QOverload::of(&QComboBox::activated), + this, &Window::accessChanged); //! [5] //! [6] diff --git a/examples/widgets/widgets/mousebuttons/main.cpp b/examples/widgets/widgets/mousebuttons/main.cpp index 28be0ffddf..e35a442181 100644 --- a/examples/widgets/widgets/mousebuttons/main.cpp +++ b/examples/widgets/widgets/mousebuttons/main.cpp @@ -68,7 +68,7 @@ int main(int argv, char **args) testArea->setText("To test your mouse with Qt, press buttons in this area.\nYou may also scroll or tilt your mouse wheel."); QPushButton *quitButton = new QPushButton("Quit"); - QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); + QObject::connect(quitButton, &QPushButton::clicked, qApp, &QCoreApplication::quit); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(testArea); diff --git a/examples/widgets/widgets/movie/movieplayer.cpp b/examples/widgets/widgets/movie/movieplayer.cpp index 61e85537a3..3003bfb541 100644 --- a/examples/widgets/widgets/movie/movieplayer.cpp +++ b/examples/widgets/widgets/movie/movieplayer.cpp @@ -69,13 +69,12 @@ MoviePlayer::MoviePlayer(QWidget *parent) createControls(); createButtons(); - connect(movie, SIGNAL(frameChanged(int)), this, SLOT(updateFrameSlider())); - connect(movie, SIGNAL(stateChanged(QMovie::MovieState)), - this, SLOT(updateButtons())); - connect(fitCheckBox, SIGNAL(clicked()), this, SLOT(fitToWindow())); - connect(frameSlider, SIGNAL(valueChanged(int)), this, SLOT(goToFrame(int))); - connect(speedSpinBox, SIGNAL(valueChanged(int)), - movie, SLOT(setSpeed(int))); + connect(movie, &QMovie::frameChanged, this, &MoviePlayer::updateFrameSlider); + connect(movie, &QMovie::stateChanged, this, &MoviePlayer::updateButtons); + connect(fitCheckBox, &QCheckBox::clicked, this, &MoviePlayer::fitToWindow); + connect(frameSlider, &QSlider::valueChanged, this, &MoviePlayer::goToFrame); + connect(speedSpinBox, QOverload::of(&QSpinBox::valueChanged), + movie, &QMovie::setSpeed); mainLayout = new QVBoxLayout; mainLayout->addWidget(movieLabel); @@ -182,32 +181,32 @@ void MoviePlayer::createButtons() openButton->setIcon(style()->standardIcon(QStyle::SP_DialogOpenButton)); openButton->setIconSize(iconSize); openButton->setToolTip(tr("Open File")); - connect(openButton, SIGNAL(clicked()), this, SLOT(open())); + connect(openButton, &QToolButton::clicked, this, &MoviePlayer::open); playButton = new QToolButton; playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay)); playButton->setIconSize(iconSize); playButton->setToolTip(tr("Play")); - connect(playButton, SIGNAL(clicked()), movie, SLOT(start())); + connect(playButton, &QToolButton::clicked, movie, &QMovie::start); pauseButton = new QToolButton; pauseButton->setCheckable(true); pauseButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause)); pauseButton->setIconSize(iconSize); pauseButton->setToolTip(tr("Pause")); - connect(pauseButton, SIGNAL(clicked(bool)), movie, SLOT(setPaused(bool))); + connect(pauseButton, &QToolButton::clicked, movie, &QMovie::setPaused); stopButton = new QToolButton; stopButton->setIcon(style()->standardIcon(QStyle::SP_MediaStop)); stopButton->setIconSize(iconSize); stopButton->setToolTip(tr("Stop")); - connect(stopButton, SIGNAL(clicked()), movie, SLOT(stop())); + connect(stopButton, &QToolButton::clicked, movie, &QMovie::stop); quitButton = new QToolButton; quitButton->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton)); quitButton->setIconSize(iconSize); quitButton->setToolTip(tr("Quit")); - connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); + connect(quitButton, &QToolButton::clicked, this, &MoviePlayer::close); buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(); diff --git a/examples/widgets/widgets/scribble/mainwindow.cpp b/examples/widgets/widgets/scribble/mainwindow.cpp index b8d01d505c..58dc42c076 100644 --- a/examples/widgets/widgets/scribble/mainwindow.cpp +++ b/examples/widgets/widgets/scribble/mainwindow.cpp @@ -151,40 +151,40 @@ void MainWindow::createActions() { openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); - connect(openAct, SIGNAL(triggered()), this, SLOT(open())); + connect(openAct, &QAction::triggered, this, &MainWindow::open); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); - connect(action, SIGNAL(triggered()), this, SLOT(save())); + connect(action, &QAction::triggered, this, &MainWindow::save); saveAsActs.append(action); } printAct = new QAction(tr("&Print..."), this); - connect(printAct, SIGNAL(triggered()), scribbleArea, SLOT(print())); + connect(printAct, &QAction::triggered, scribbleArea, &ScribbleArea::print); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit); - connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); + connect(exitAct, &QAction::triggered, this, &MainWindow::close); penColorAct = new QAction(tr("&Pen Color..."), this); - connect(penColorAct, SIGNAL(triggered()), this, SLOT(penColor())); + connect(penColorAct, &QAction::triggered, this, &MainWindow::penColor); penWidthAct = new QAction(tr("Pen &Width..."), this); - connect(penWidthAct, SIGNAL(triggered()), this, SLOT(penWidth())); + connect(penWidthAct, &QAction::triggered, this, &MainWindow::penWidth); clearScreenAct = new QAction(tr("&Clear Screen"), this); clearScreenAct->setShortcut(tr("Ctrl+L")); - connect(clearScreenAct, SIGNAL(triggered()), - scribbleArea, SLOT(clearImage())); + connect(clearScreenAct, &QAction::triggered, + scribbleArea, &ScribbleArea::clearImage); aboutAct = new QAction(tr("&About"), this); - connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); + connect(aboutAct, &QAction::triggered, this, &MainWindow::about); aboutQtAct = new QAction(tr("About &Qt"), this); - connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + connect(aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); } //! [14] diff --git a/examples/widgets/widgets/shapedclock/shapedclock.cpp b/examples/widgets/widgets/shapedclock/shapedclock.cpp index af0cd01be5..8e7d831938 100644 --- a/examples/widgets/widgets/shapedclock/shapedclock.cpp +++ b/examples/widgets/widgets/shapedclock/shapedclock.cpp @@ -57,12 +57,12 @@ ShapedClock::ShapedClock(QWidget *parent) : QWidget(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint) { QTimer *timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), this, SLOT(update())); + connect(timer, &QTimer::timeout, this, QOverload<>::of(&ShapedClock::update)); timer->start(1000); QAction *quitAction = new QAction(tr("E&xit"), this); quitAction->setShortcut(tr("Ctrl+Q")); - connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit); addAction(quitAction); setContextMenuPolicy(Qt::ActionsContextMenu); diff --git a/examples/widgets/widgets/sliders/slidersgroup.cpp b/examples/widgets/widgets/sliders/slidersgroup.cpp index 365a003047..3bccdd687a 100644 --- a/examples/widgets/widgets/sliders/slidersgroup.cpp +++ b/examples/widgets/widgets/sliders/slidersgroup.cpp @@ -69,11 +69,11 @@ SlidersGroup::SlidersGroup(Qt::Orientation orientation, const QString &title, dial = new QDial; dial->setFocusPolicy(Qt::StrongFocus); - connect(slider, SIGNAL(valueChanged(int)), scrollBar, SLOT(setValue(int))); - connect(scrollBar, SIGNAL(valueChanged(int)), dial, SLOT(setValue(int))); - connect(dial, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int))); + connect(slider, &QSlider::valueChanged, scrollBar, &QScrollBar::setValue); + connect(scrollBar, &QScrollBar::valueChanged, dial, &QDial::setValue); + connect(dial, &QDial::valueChanged, slider, &QSlider::setValue); //! [0] //! [1] - connect(dial, SIGNAL(valueChanged(int)), this, SIGNAL(valueChanged(int))); + connect(dial, &QDial::valueChanged, this, &SlidersGroup::valueChanged); //! [1] //! [2] //! [2] //! [3] diff --git a/examples/widgets/widgets/sliders/window.cpp b/examples/widgets/widgets/sliders/window.cpp index 16467e71be..d73fafec10 100644 --- a/examples/widgets/widgets/sliders/window.cpp +++ b/examples/widgets/widgets/sliders/window.cpp @@ -68,13 +68,13 @@ Window::Window(QWidget *parent) //! [0] //! [1] - connect(horizontalSliders, SIGNAL(valueChanged(int)), + connect(horizontalSliders, &SlidersGroup::valueChanged, //! [1] //! [2] - verticalSliders, SLOT(setValue(int))); - connect(verticalSliders, SIGNAL(valueChanged(int)), - valueSpinBox, SLOT(setValue(int))); - connect(valueSpinBox, SIGNAL(valueChanged(int)), - horizontalSliders, SLOT(setValue(int))); + verticalSliders, &SlidersGroup::setValue); + connect(verticalSliders, &SlidersGroup::valueChanged, + valueSpinBox, &QSpinBox::setValue); + connect(valueSpinBox, QOverload::of(&QSpinBox::valueChanged), + horizontalSliders, &SlidersGroup::setValue); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(controlsGroup); @@ -121,25 +121,25 @@ void Window::createControls(const QString &title) orientationCombo->addItem(tr("Vertical slider-like widgets")); //! [6] //! [7] - connect(orientationCombo, SIGNAL(activated(int)), + connect(orientationCombo, QOverload::of(&QComboBox::activated), //! [7] //! [8] - stackedWidget, SLOT(setCurrentIndex(int))); - connect(minimumSpinBox, SIGNAL(valueChanged(int)), - horizontalSliders, SLOT(setMinimum(int))); - connect(minimumSpinBox, SIGNAL(valueChanged(int)), - verticalSliders, SLOT(setMinimum(int))); - connect(maximumSpinBox, SIGNAL(valueChanged(int)), - horizontalSliders, SLOT(setMaximum(int))); - connect(maximumSpinBox, SIGNAL(valueChanged(int)), - verticalSliders, SLOT(setMaximum(int))); - connect(invertedAppearance, SIGNAL(toggled(bool)), - horizontalSliders, SLOT(invertAppearance(bool))); - connect(invertedAppearance, SIGNAL(toggled(bool)), - verticalSliders, SLOT(invertAppearance(bool))); - connect(invertedKeyBindings, SIGNAL(toggled(bool)), - horizontalSliders, SLOT(invertKeyBindings(bool))); - connect(invertedKeyBindings, SIGNAL(toggled(bool)), - verticalSliders, SLOT(invertKeyBindings(bool))); + stackedWidget, &QStackedWidget::setCurrentIndex); + connect(minimumSpinBox, QOverload::of(&QSpinBox::valueChanged), + horizontalSliders, &SlidersGroup::setMinimum); + connect(minimumSpinBox, QOverload::of(&QSpinBox::valueChanged), + verticalSliders, &SlidersGroup::setMinimum); + connect(maximumSpinBox, QOverload::of(&QSpinBox::valueChanged), + horizontalSliders, &SlidersGroup::setMaximum); + connect(maximumSpinBox, QOverload::of(&QSpinBox::valueChanged), + verticalSliders, &SlidersGroup::setMaximum); + connect(invertedAppearance, &QCheckBox::toggled, + horizontalSliders, &SlidersGroup::invertAppearance); + connect(invertedAppearance, &QCheckBox::toggled, + verticalSliders, &SlidersGroup::invertAppearance); + connect(invertedKeyBindings, &QCheckBox::toggled, + horizontalSliders, &SlidersGroup::invertKeyBindings); + connect(invertedKeyBindings, &QCheckBox::toggled, + verticalSliders, &SlidersGroup::invertKeyBindings); QGridLayout *controlsLayout = new QGridLayout; controlsLayout->addWidget(minimumLabel, 0, 0); diff --git a/examples/widgets/widgets/spinboxes/window.cpp b/examples/widgets/widgets/spinboxes/window.cpp index eb660faace..fd7c5b527e 100644 --- a/examples/widgets/widgets/spinboxes/window.cpp +++ b/examples/widgets/widgets/spinboxes/window.cpp @@ -176,8 +176,8 @@ void Window::createDateTimeEdits() formatComboBox->addItem("hh:mm ap"); //! [9] //! [10] - connect(formatComboBox, SIGNAL(activated(QString)), - this, SLOT(setFormatString(QString))); + connect(formatComboBox, QOverload::of(&QComboBox::activated), + this, &Window::setFormatString); //! [10] setFormatString(formatComboBox->currentText()); @@ -256,9 +256,9 @@ void Window::createDoubleSpinBoxes() priceSpinBox->setPrefix("$"); priceSpinBox->setValue(99.99); - connect(precisionSpinBox, SIGNAL(valueChanged(int)), + connect(precisionSpinBox, QOverload::of(&QSpinBox::valueChanged), //! [17] - this, SLOT(changePrecision(int))); + this, &Window::changePrecision); groupSeparatorSpinBox_d = new QDoubleSpinBox; groupSeparatorSpinBox_d->setRange(-99999999, 99999999); diff --git a/examples/widgets/widgets/styles/widgetgallery.cpp b/examples/widgets/widgets/styles/widgetgallery.cpp index d44547d905..dbe82c547b 100644 --- a/examples/widgets/widgets/styles/widgetgallery.cpp +++ b/examples/widgets/widgets/styles/widgetgallery.cpp @@ -79,19 +79,19 @@ WidgetGallery::WidgetGallery(QWidget *parent) //! [0] //! [1] - connect(styleComboBox, SIGNAL(activated(QString)), + connect(styleComboBox, QOverload::of(&QComboBox::activated), //! [1] //! [2] - this, SLOT(changeStyle(QString))); - connect(useStylePaletteCheckBox, SIGNAL(toggled(bool)), - this, SLOT(changePalette())); - connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), - topLeftGroupBox, SLOT(setDisabled(bool))); - connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), - topRightGroupBox, SLOT(setDisabled(bool))); - connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), - bottomLeftTabWidget, SLOT(setDisabled(bool))); - connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), - bottomRightGroupBox, SLOT(setDisabled(bool))); + this, &WidgetGallery::changeStyle); + connect(useStylePaletteCheckBox, &QCheckBox::toggled, + this, &WidgetGallery::changePalette); + connect(disableWidgetsCheckBox, &QCheckBox::toggled, + topLeftGroupBox, &QGroupBox::setDisabled); + connect(disableWidgetsCheckBox, &QCheckBox::toggled, + topRightGroupBox, &QGroupBox::setDisabled); + connect(disableWidgetsCheckBox, &QCheckBox::toggled, + bottomLeftTabWidget, &QGroupBox::setDisabled); + connect(disableWidgetsCheckBox, &QCheckBox::toggled, + bottomRightGroupBox, &QGroupBox::setDisabled); //! [2] //! [3] @@ -279,7 +279,7 @@ void WidgetGallery::createProgressBar() progressBar->setValue(0); QTimer *timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), this, SLOT(advanceProgressBar())); + connect(timer, &QTimer::timeout, this, &WidgetGallery::advanceProgressBar); timer->start(1000); } //! [13] diff --git a/examples/widgets/widgets/stylesheet/mainwindow.cpp b/examples/widgets/widgets/stylesheet/mainwindow.cpp index eb4b3a2424..f187c007dd 100644 --- a/examples/widgets/widgets/stylesheet/mainwindow.cpp +++ b/examples/widgets/widgets/stylesheet/mainwindow.cpp @@ -64,8 +64,8 @@ MainWindow::MainWindow(QWidget *parent) statusBar()->addWidget(new QLabel(tr("Ready"))); - connect(ui.exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - connect(ui.aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + connect(ui.exitAction, &QAction::triggered, qApp, &QApplication::quit); + connect(ui.aboutQtAction, &QAction::triggered, qApp, &QApplication::aboutQt); } void MainWindow::on_editStyleAction_triggered() diff --git a/examples/widgets/widgets/validators/ledwidget.cpp b/examples/widgets/widgets/validators/ledwidget.cpp index 65248741b5..462f416c86 100644 --- a/examples/widgets/widgets/validators/ledwidget.cpp +++ b/examples/widgets/widgets/validators/ledwidget.cpp @@ -56,7 +56,7 @@ LEDWidget::LEDWidget(QWidget *parent) setPixmap(offPixmap); flashTimer.setInterval(200); flashTimer.setSingleShot(true); - connect(&flashTimer, SIGNAL(timeout()), this, SLOT(extinguish())); + connect(&flashTimer, &QTimer::timeout, this, &LEDWidget::extinguish); }; void LEDWidget::extinguish() diff --git a/examples/widgets/widgets/validators/localeselector.cpp b/examples/widgets/widgets/validators/localeselector.cpp index 2f702c9753..7253fea9ec 100644 --- a/examples/widgets/widgets/validators/localeselector.cpp +++ b/examples/widgets/widgets/validators/localeselector.cpp @@ -79,7 +79,8 @@ LocaleSelector::LocaleSelector(QWidget *parent) if (curIndex != -1) setCurrentIndex(curIndex); - connect(this, SIGNAL(activated(int)), this, SLOT(emitLocaleSelected(int))); + connect(this, QOverload::of(&LocaleSelector::activated), + this, &LocaleSelector::emitLocaleSelected); } void LocaleSelector::emitLocaleSelected(int index) diff --git a/examples/widgets/widgets/windowflags/controllerwindow.cpp b/examples/widgets/widgets/windowflags/controllerwindow.cpp index c19f23c513..e2abad89f4 100644 --- a/examples/widgets/widgets/windowflags/controllerwindow.cpp +++ b/examples/widgets/widgets/windowflags/controllerwindow.cpp @@ -62,7 +62,8 @@ ControllerWindow::ControllerWindow(QWidget *parent) createHintsGroupBox(); quitButton = new QPushButton(tr("&Quit")); - connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); + connect(quitButton, &QPushButton::clicked, + qApp, &QApplication::quit); QHBoxLayout *bottomLayout = new QHBoxLayout; bottomLayout->addStretch(); @@ -220,7 +221,8 @@ void ControllerWindow::createHintsGroupBox() QCheckBox *ControllerWindow::createCheckBox(const QString &text) { QCheckBox *checkBox = new QCheckBox(text); - connect(checkBox, SIGNAL(clicked()), this, SLOT(updatePreview())); + connect(checkBox, &QCheckBox::clicked, + this, &ControllerWindow::updatePreview); return checkBox; } //! [7] @@ -229,7 +231,8 @@ QCheckBox *ControllerWindow::createCheckBox(const QString &text) QRadioButton *ControllerWindow::createRadioButton(const QString &text) { QRadioButton *button = new QRadioButton(text); - connect(button, SIGNAL(clicked()), this, SLOT(updatePreview())); + connect(button, &QRadioButton::clicked, + this, &ControllerWindow::updatePreview); return button; } //! [8] diff --git a/examples/widgets/widgets/windowflags/previewwindow.cpp b/examples/widgets/widgets/windowflags/previewwindow.cpp index 725a134daf..09e26fd7e4 100644 --- a/examples/widgets/widgets/windowflags/previewwindow.cpp +++ b/examples/widgets/widgets/windowflags/previewwindow.cpp @@ -61,7 +61,8 @@ PreviewWindow::PreviewWindow(QWidget *parent) textEdit->setLineWrapMode(QTextEdit::NoWrap); closeButton = new QPushButton(tr("&Close")); - connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); + connect(closeButton, &QPushButton::clicked, + this, &PreviewWindow::close); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(textEdit); -- cgit v1.2.3 From 9f971ca816ea0aac7b0f639c031a379731632722 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 27 Jan 2019 17:47:01 +0100 Subject: QtWidgets: replace 0 with \nullptr in documentation Replace 0 with \nullptr in the documentation. As a drive-by also replace some 0 with nullptr in the corresponding code. Change-Id: I8d7e9c838da1399988a830669d58fc7f2f010696 Reviewed-by: Friedemann Kleint Reviewed-by: Paul Wicking --- examples/widgets/animation/sub-attaq/qanimationstate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples/widgets') diff --git a/examples/widgets/animation/sub-attaq/qanimationstate.cpp b/examples/widgets/animation/sub-attaq/qanimationstate.cpp index ef88df8abe..ce99f9080d 100644 --- a/examples/widgets/animation/sub-attaq/qanimationstate.cpp +++ b/examples/widgets/animation/sub-attaq/qanimationstate.cpp @@ -118,7 +118,7 @@ void QAnimationState::setAnimation(QAbstractAnimation *animation) } /*! - Returns the animation handle by this animation state, or 0 if there is no animation. + Returns the animation handle by this animation state, or \nullptr if there is no animation. */ QAbstractAnimation* QAnimationState::animation() const { -- cgit v1.2.3 From 64b2eb7490f502feececec314eb215bbb7832858 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Tue, 4 Dec 2018 17:27:16 +0100 Subject: Cleanup Widgets examples - replace foreach Cleanup the Widget examples - replace foreach with a standard for loop Change-Id: I59cb2bf4494201f9f0228b07a8bb936ce40da46f Reviewed-by: Samuel Gaist Reviewed-by: Konstantin Shegunov Reviewed-by: Edward Welbourne Reviewed-by: Paul Wicking --- examples/widgets/widgets/charactermap/mainwindow.cpp | 11 ++++++----- examples/widgets/widgets/icons/mainwindow.cpp | 16 ++++++++++------ examples/widgets/widgets/imageviewer/imageviewer.cpp | 2 +- examples/widgets/widgets/scribble/mainwindow.cpp | 7 ++++--- examples/widgets/widgets/tooltips/sortingbox.cpp | 2 +- examples/widgets/widgets/validators/localeselector.cpp | 4 +++- 6 files changed, 25 insertions(+), 17 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/charactermap/mainwindow.cpp b/examples/widgets/widgets/charactermap/mainwindow.cpp index 1b6f77bf30..e84ded5afb 100644 --- a/examples/widgets/widgets/charactermap/mainwindow.cpp +++ b/examples/widgets/widgets/charactermap/mainwindow.cpp @@ -170,8 +170,8 @@ void MainWindow::findStyles(const QFont &font) //! [7] //! [8] - QString style; - foreach (style, fontDatabase.styles(font.family())) + const QStringList styles = fontDatabase.styles(font.family()); + for (const QString &style : styles) styleCombo->addItem(style); int styleIndex = styleCombo->findText(currentItem); @@ -201,15 +201,16 @@ void MainWindow::findSizes(const QFont &font) // sizeCombo signals are now blocked until end of scope sizeCombo->clear(); - int size; if (fontDatabase.isSmoothlyScalable(font.family(), fontDatabase.styleString(font))) { - foreach (size, QFontDatabase::standardSizes()) { + const QList sizes = QFontDatabase::standardSizes(); + for (const int size : sizes) { sizeCombo->addItem(QVariant(size).toString()); sizeCombo->setEditable(true); } } else { - foreach (size, fontDatabase.smoothSizes(font.family(), fontDatabase.styleString(font))) { + const QList sizes = fontDatabase.smoothSizes(font.family(), fontDatabase.styleString(font)); + for (const int size : sizes ) { sizeCombo->addItem(QVariant(size).toString()); sizeCombo->setEditable(false); } diff --git a/examples/widgets/widgets/icons/mainwindow.cpp b/examples/widgets/widgets/icons/mainwindow.cpp index 904245494c..0cf11c978d 100644 --- a/examples/widgets/widgets/icons/mainwindow.cpp +++ b/examples/widgets/widgets/icons/mainwindow.cpp @@ -122,7 +122,8 @@ void MainWindow::changeStyle(bool checked) Q_ASSERT(style); QApplication::setStyle(style); - foreach (QAbstractButton *button, sizeButtonGroup->buttons()) { + const QList buttons = sizeButtonGroup->buttons(); + for (QAbstractButton *button : buttons) { const QStyle::PixelMetric metric = static_cast(sizeButtonGroup->id(button)); const int value = style->pixelMetric(metric); switch (metric) { @@ -230,7 +231,8 @@ void MainWindow::addImages(const QString &directory) { QFileDialog fileDialog(this, tr("Open Images"), directory); QStringList mimeTypeFilters; - foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes()) + const QList mimeTypes = QImageReader::supportedMimeTypes(); + for (const QByteArray &mimeTypeName : mimeTypes) mimeTypeFilters.append(mimeTypeName); mimeTypeFilters.sort(); fileDialog.setMimeTypeFilters(mimeTypeFilters); @@ -246,7 +248,7 @@ void MainWindow::addImages(const QString &directory) void MainWindow::loadImages(const QStringList &fileNames) { - foreach (const QString &fileName, fileNames) { + for (const QString &fileName : fileNames) { const int row = imagesTable->rowCount(); imagesTable->setRowCount(row + 1); //! [13] @@ -469,7 +471,8 @@ void MainWindow::createActions() QMenu *viewMenu = menuBar()->addMenu(tr("&View")); styleActionGroup = new QActionGroup(this); - foreach (const QString &styleName, QStyleFactory::keys()) { + const QStringList styleKeys = QStyleFactory::keys(); + for (const QString &styleName : styleKeys) { QAction *action = new QAction(tr("%1 Style").arg(styleName), styleActionGroup); action->setData(styleName); action->setCheckable(true); @@ -508,8 +511,9 @@ void MainWindow::createContextMenu() //! [31] void MainWindow::checkCurrentStyle() { - foreach (QAction *action, styleActionGroup->actions()) { - QString styleName = action->data().toString(); + const QList actions = styleActionGroup->actions(); + for (QAction *action : actions) { + const QString styleName = action->data().toString(); QScopedPointer candidate(QStyleFactory::create(styleName)); Q_ASSERT(!candidate.isNull()); if (candidate->metaObject()->className() diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp index b1346d9ccb..70623dc7cb 100644 --- a/examples/widgets/widgets/imageviewer/imageviewer.cpp +++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp @@ -151,7 +151,7 @@ static void initializeImageFileDialog(QFileDialog &dialog, QFileDialog::AcceptMo QStringList mimeTypeFilters; const QByteArrayList supportedMimeTypes = acceptMode == QFileDialog::AcceptOpen ? QImageReader::supportedMimeTypes() : QImageWriter::supportedMimeTypes(); - foreach (const QByteArray &mimeTypeName, supportedMimeTypes) + for (const QByteArray &mimeTypeName : supportedMimeTypes) mimeTypeFilters.append(mimeTypeName); mimeTypeFilters.sort(); dialog.setMimeTypeFilters(mimeTypeFilters); diff --git a/examples/widgets/widgets/scribble/mainwindow.cpp b/examples/widgets/widgets/scribble/mainwindow.cpp index 58dc42c076..44afa64b94 100644 --- a/examples/widgets/widgets/scribble/mainwindow.cpp +++ b/examples/widgets/widgets/scribble/mainwindow.cpp @@ -153,8 +153,9 @@ void MainWindow::createActions() openAct->setShortcuts(QKeySequence::Open); connect(openAct, &QAction::triggered, this, &MainWindow::open); - foreach (QByteArray format, QImageWriter::supportedImageFormats()) { - QString text = tr("%1...").arg(QString(format).toUpper()); + const QList imageFormats = QImageWriter::supportedImageFormats(); + for (const QByteArray &format : imageFormats) { + QString text = tr("%1...").arg(QString::fromLatin1(format).toUpper()); QAction *action = new QAction(text, this); action->setData(format); @@ -193,7 +194,7 @@ void MainWindow::createMenus() //! [15] //! [16] { saveAsMenu = new QMenu(tr("&Save As"), this); - foreach (QAction *action, saveAsActs) + for (QAction *action : qAsConst(saveAsActs)) saveAsMenu->addAction(action); fileMenu = new QMenu(tr("&File"), this); diff --git a/examples/widgets/widgets/tooltips/sortingbox.cpp b/examples/widgets/widgets/tooltips/sortingbox.cpp index 5f8d96f110..838083c399 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.cpp +++ b/examples/widgets/widgets/tooltips/sortingbox.cpp @@ -140,7 +140,7 @@ void SortingBox::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); - foreach (ShapeItem shapeItem, shapeItems) { + for (const ShapeItem &shapeItem : qAsConst(shapeItems)) { //! [8] //! [9] painter.translate(shapeItem.position()); //! [9] //! [10] diff --git a/examples/widgets/widgets/validators/localeselector.cpp b/examples/widgets/widgets/validators/localeselector.cpp index 7253fea9ec..1382da0cc9 100644 --- a/examples/widgets/widgets/validators/localeselector.cpp +++ b/examples/widgets/widgets/validators/localeselector.cpp @@ -59,7 +59,9 @@ LocaleSelector::LocaleSelector(QWidget *parent) int index = 0; for (int _lang = QLocale::C; _lang <= QLocale::LastLanguage; ++_lang) { QLocale::Language lang = static_cast(_lang); - foreach (const QLocale &l, QLocale::matchingLocales(lang, QLocale::AnyScript, QLocale::AnyCountry)) { + const QList locales = + QLocale::matchingLocales(lang, QLocale::AnyScript, QLocale::AnyCountry); + for (const QLocale &l : locales) { QString label = QLocale::languageToString(l.language()); label += QLatin1Char('/'); label += QLocale::countryToString(l.country()); -- cgit v1.2.3 From 004d7168a335219b19805badae0590b0f5dcfad0 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 2 Dec 2018 14:18:38 +0100 Subject: Cleanup Widgets examples - includes Cleanup the Widgets examples - adjust includes to Qt coding style and remove unused includes and formward declarations Change-Id: I9f2e513284ad631337ff52ec9c0b98645055dcca Reviewed-by: Konstantin Shegunov Reviewed-by: Paul Wicking --- examples/widgets/widgets/analogclock/analogclock.cpp | 4 ++-- examples/widgets/widgets/calculator/button.cpp | 4 ++-- examples/widgets/widgets/calculator/calculator.cpp | 6 +++--- examples/widgets/widgets/charactermap/characterwidget.cpp | 4 ++-- examples/widgets/widgets/charactermap/characterwidget.h | 1 - examples/widgets/widgets/codeeditor/codeeditor.h | 1 - examples/widgets/widgets/digitalclock/digitalclock.cpp | 4 ++-- examples/widgets/widgets/elidedlabel/elidedlabel.cpp | 2 +- examples/widgets/widgets/elidedlabel/elidedlabel.h | 7 ++----- examples/widgets/widgets/elidedlabel/main.cpp | 2 +- examples/widgets/widgets/elidedlabel/testwidget.cpp | 13 ++++++------- examples/widgets/widgets/elidedlabel/testwidget.h | 7 +++---- examples/widgets/widgets/icons/iconpreviewarea.cpp | 4 ++-- examples/widgets/widgets/icons/iconsizespinbox.cpp | 4 ++-- examples/widgets/widgets/icons/imagedelegate.cpp | 4 ++-- examples/widgets/widgets/icons/mainwindow.h | 2 -- examples/widgets/widgets/imageviewer/imageviewer.cpp | 4 ++-- examples/widgets/widgets/lineedits/window.h | 1 - examples/widgets/widgets/movie/movieplayer.cpp | 4 ++-- examples/widgets/widgets/scribble/scribblearea.cpp | 4 ++-- examples/widgets/widgets/sliders/slidersgroup.cpp | 4 ++-- examples/widgets/widgets/styles/norwegianwoodstyle.cpp | 4 ++-- examples/widgets/widgets/styles/widgetgallery.cpp | 6 +++--- examples/widgets/widgets/stylesheet/stylesheeteditor.cpp | 4 ++-- examples/widgets/widgets/tablet/tabletapplication.cpp | 4 ++-- examples/widgets/widgets/tetrix/main.cpp | 6 ++---- examples/widgets/widgets/tetrix/tetrixboard.cpp | 4 ++-- examples/widgets/widgets/tetrix/tetrixpiece.cpp | 6 ++---- examples/widgets/widgets/tetrix/tetrixwindow.h | 1 - examples/widgets/widgets/tooltips/shapeitem.cpp | 2 -- examples/widgets/widgets/tooltips/sortingbox.cpp | 6 ++---- examples/widgets/widgets/tooltips/sortingbox.h | 4 ++-- examples/widgets/widgets/wiggly/dialog.cpp | 6 +++--- examples/widgets/widgets/wiggly/main.cpp | 4 ++-- examples/widgets/widgets/wiggly/wigglywidget.cpp | 4 ++-- examples/widgets/widgets/windowflags/previewwindow.cpp | 4 ++-- 36 files changed, 66 insertions(+), 85 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/analogclock/analogclock.cpp b/examples/widgets/widgets/analogclock/analogclock.cpp index bee316b9b7..c7b3f66cca 100644 --- a/examples/widgets/widgets/analogclock/analogclock.cpp +++ b/examples/widgets/widgets/analogclock/analogclock.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "analogclock.h" +#include + //! [0] //! [1] AnalogClock::AnalogClock(QWidget *parent) //! [0] //! [2] diff --git a/examples/widgets/widgets/calculator/button.cpp b/examples/widgets/widgets/calculator/button.cpp index 0d622b1781..a1ce0bf428 100644 --- a/examples/widgets/widgets/calculator/button.cpp +++ b/examples/widgets/widgets/calculator/button.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "button.h" +#include + //! [0] Button::Button(const QString &text, QWidget *parent) : QToolButton(parent) diff --git a/examples/widgets/widgets/calculator/calculator.cpp b/examples/widgets/widgets/calculator/calculator.cpp index cbcc29b2a8..dd908cf40a 100644 --- a/examples/widgets/widgets/calculator/calculator.cpp +++ b/examples/widgets/widgets/calculator/calculator.cpp @@ -48,13 +48,13 @@ ** ****************************************************************************/ +#include "button.h" +#include "calculator.h" + #include #include -#include "button.h" -#include "calculator.h" - //! [0] Calculator::Calculator(QWidget *parent) : QWidget(parent) diff --git a/examples/widgets/widgets/charactermap/characterwidget.cpp b/examples/widgets/widgets/charactermap/characterwidget.cpp index 5bab921516..061c0164b0 100644 --- a/examples/widgets/widgets/charactermap/characterwidget.cpp +++ b/examples/widgets/widgets/charactermap/characterwidget.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "characterwidget.h" +#include + //! [0] CharacterWidget::CharacterWidget(QWidget *parent) : QWidget(parent), columns(16), lastKey(-1) diff --git a/examples/widgets/widgets/charactermap/characterwidget.h b/examples/widgets/widgets/charactermap/characterwidget.h index 34e061e96b..d12a46aa15 100644 --- a/examples/widgets/widgets/charactermap/characterwidget.h +++ b/examples/widgets/widgets/charactermap/characterwidget.h @@ -52,7 +52,6 @@ #define CHARACTERWIDGET_H #include -#include #include #include #include diff --git a/examples/widgets/widgets/codeeditor/codeeditor.h b/examples/widgets/widgets/codeeditor/codeeditor.h index fcfc188cf2..5a48abafc4 100644 --- a/examples/widgets/widgets/codeeditor/codeeditor.h +++ b/examples/widgets/widgets/codeeditor/codeeditor.h @@ -52,7 +52,6 @@ #define CODEEDITOR_H #include -#include QT_BEGIN_NAMESPACE class QPaintEvent; diff --git a/examples/widgets/widgets/digitalclock/digitalclock.cpp b/examples/widgets/widgets/digitalclock/digitalclock.cpp index dec7e64fc3..000334f33b 100644 --- a/examples/widgets/widgets/digitalclock/digitalclock.cpp +++ b/examples/widgets/widgets/digitalclock/digitalclock.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "digitalclock.h" +#include + //! [0] DigitalClock::DigitalClock(QWidget *parent) : QLCDNumber(parent) diff --git a/examples/widgets/widgets/elidedlabel/elidedlabel.cpp b/examples/widgets/widgets/elidedlabel/elidedlabel.cpp index b12bf118f6..e80f7a9894 100644 --- a/examples/widgets/widgets/elidedlabel/elidedlabel.cpp +++ b/examples/widgets/widgets/elidedlabel/elidedlabel.cpp @@ -51,8 +51,8 @@ #include "elidedlabel.h" #include +#include #include -#include //! [0] ElidedLabel::ElidedLabel(const QString &text, QWidget *parent) diff --git a/examples/widgets/widgets/elidedlabel/elidedlabel.h b/examples/widgets/widgets/elidedlabel/elidedlabel.h index 9d4fe5fef3..0c8d96834e 100644 --- a/examples/widgets/widgets/elidedlabel/elidedlabel.h +++ b/examples/widgets/widgets/elidedlabel/elidedlabel.h @@ -51,11 +51,8 @@ #ifndef ELIDEDLABEL_H #define ELIDEDLABEL_H -#include -#include -#include -#include -#include +#include +#include //! [0] class ElidedLabel : public QFrame diff --git a/examples/widgets/widgets/elidedlabel/main.cpp b/examples/widgets/widgets/elidedlabel/main.cpp index f692db0efc..1c620c1d41 100644 --- a/examples/widgets/widgets/elidedlabel/main.cpp +++ b/examples/widgets/widgets/elidedlabel/main.cpp @@ -50,7 +50,7 @@ #include "testwidget.h" -#include +#include //! [0] int main( int argc, char *argv[] ) diff --git a/examples/widgets/widgets/elidedlabel/testwidget.cpp b/examples/widgets/widgets/elidedlabel/testwidget.cpp index 6392a4b4fa..4e013cc5de 100644 --- a/examples/widgets/widgets/elidedlabel/testwidget.cpp +++ b/examples/widgets/widgets/elidedlabel/testwidget.cpp @@ -51,14 +51,13 @@ #include "testwidget.h" #include "elidedlabel.h" -#include -#include -#include -#include +#include +#include +#include //! [0] -TestWidget::TestWidget(QWidget *parent): - QWidget(parent) +TestWidget::TestWidget(QWidget *parent) + : QWidget(parent) { const QString romeo = tr( "But soft, what light through yonder window breaks? / " @@ -116,7 +115,7 @@ TestWidget::TestWidget(QWidget *parent): //! [3] //! [4] - QGridLayout *layout = new QGridLayout(); + QGridLayout *layout = new QGridLayout; layout->addWidget(label, 0, 1, Qt::AlignCenter); layout->addWidget(switchButton, 0, 2); layout->addWidget(exitButton, 0, 3); diff --git a/examples/widgets/widgets/elidedlabel/testwidget.h b/examples/widgets/widgets/elidedlabel/testwidget.h index cd309d2316..bcb2f33044 100644 --- a/examples/widgets/widgets/elidedlabel/testwidget.h +++ b/examples/widgets/widgets/elidedlabel/testwidget.h @@ -51,10 +51,9 @@ #ifndef TESTWIDGET_H #define TESTWIDGET_H -#include -#include -#include -#include +#include +#include +#include class ElidedLabel; diff --git a/examples/widgets/widgets/icons/iconpreviewarea.cpp b/examples/widgets/widgets/icons/iconpreviewarea.cpp index 9cb54c47f6..1a2f514ba8 100644 --- a/examples/widgets/widgets/icons/iconpreviewarea.cpp +++ b/examples/widgets/widgets/icons/iconpreviewarea.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "iconpreviewarea.h" +#include + //! [0] IconPreviewArea::IconPreviewArea(QWidget *parent) : QWidget(parent) diff --git a/examples/widgets/widgets/icons/iconsizespinbox.cpp b/examples/widgets/widgets/icons/iconsizespinbox.cpp index 4c6a850858..e94d943993 100644 --- a/examples/widgets/widgets/icons/iconsizespinbox.cpp +++ b/examples/widgets/widgets/icons/iconsizespinbox.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "iconsizespinbox.h" +#include + //! [0] IconSizeSpinBox::IconSizeSpinBox(QWidget *parent) : QSpinBox(parent) diff --git a/examples/widgets/widgets/icons/imagedelegate.cpp b/examples/widgets/widgets/icons/imagedelegate.cpp index 3c873f1e24..786194bae7 100644 --- a/examples/widgets/widgets/icons/imagedelegate.cpp +++ b/examples/widgets/widgets/icons/imagedelegate.cpp @@ -48,11 +48,11 @@ ** ****************************************************************************/ -#include - #include "imagedelegate.h" #include "iconpreviewarea.h" +#include + //! [0] ImageDelegate::ImageDelegate(QObject *parent) : QItemDelegate(parent) diff --git a/examples/widgets/widgets/icons/mainwindow.h b/examples/widgets/widgets/icons/mainwindow.h index 1949bd235c..c67d828cab 100644 --- a/examples/widgets/widgets/icons/mainwindow.h +++ b/examples/widgets/widgets/icons/mainwindow.h @@ -60,8 +60,6 @@ QT_BEGIN_NAMESPACE class QAction; class QActionGroup; class QLabel; -class QMenu; -class QRadioButton; class QButtonGroup; class QTableWidget; QT_END_NAMESPACE diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp index 70623dc7cb..fed551dade 100644 --- a/examples/widgets/widgets/imageviewer/imageviewer.cpp +++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp @@ -48,6 +48,8 @@ ** ****************************************************************************/ +#include "imageviewer.h" + #include #if defined(QT_PRINTSUPPORT_LIB) #include @@ -56,8 +58,6 @@ #endif #endif -#include "imageviewer.h" - //! [0] ImageViewer::ImageViewer(QWidget *parent) : QMainWindow(parent), imageLabel(new QLabel), diff --git a/examples/widgets/widgets/lineedits/window.h b/examples/widgets/widgets/lineedits/window.h index 3231588f4f..a31634f3a3 100644 --- a/examples/widgets/widgets/lineedits/window.h +++ b/examples/widgets/widgets/lineedits/window.h @@ -54,7 +54,6 @@ #include QT_BEGIN_NAMESPACE -class QComboBox; class QLineEdit; QT_END_NAMESPACE diff --git a/examples/widgets/widgets/movie/movieplayer.cpp b/examples/widgets/widgets/movie/movieplayer.cpp index 3003bfb541..182b258a82 100644 --- a/examples/widgets/widgets/movie/movieplayer.cpp +++ b/examples/widgets/widgets/movie/movieplayer.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "movieplayer.h" +#include + MoviePlayer::MoviePlayer(QWidget *parent) : QWidget(parent) { diff --git a/examples/widgets/widgets/scribble/scribblearea.cpp b/examples/widgets/widgets/scribble/scribblearea.cpp index d32a29697b..13e46f6e1d 100644 --- a/examples/widgets/widgets/scribble/scribblearea.cpp +++ b/examples/widgets/widgets/scribble/scribblearea.cpp @@ -48,6 +48,8 @@ ** ****************************************************************************/ +#include "scribblearea.h" + #include #if defined(QT_PRINTSUPPORT_LIB) #include @@ -57,8 +59,6 @@ #endif #endif -#include "scribblearea.h" - //! [0] ScribbleArea::ScribbleArea(QWidget *parent) : QWidget(parent) diff --git a/examples/widgets/widgets/sliders/slidersgroup.cpp b/examples/widgets/widgets/sliders/slidersgroup.cpp index 3bccdd687a..b4eaf9bb3d 100644 --- a/examples/widgets/widgets/sliders/slidersgroup.cpp +++ b/examples/widgets/widgets/sliders/slidersgroup.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "slidersgroup.h" +#include + //! [0] SlidersGroup::SlidersGroup(Qt::Orientation orientation, const QString &title, QWidget *parent) diff --git a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp index 8aca91a686..b334ca97cb 100644 --- a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp +++ b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "norwegianwoodstyle.h" +#include + NorwegianWoodStyle::NorwegianWoodStyle() : QProxyStyle(QStyleFactory::create("windows")) { diff --git a/examples/widgets/widgets/styles/widgetgallery.cpp b/examples/widgets/widgets/styles/widgetgallery.cpp index dbe82c547b..7f4b7f39d4 100644 --- a/examples/widgets/widgets/styles/widgetgallery.cpp +++ b/examples/widgets/widgets/styles/widgetgallery.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - -#include "norwegianwoodstyle.h" #include "widgetgallery.h" +#include "norwegianwoodstyle.h" + +#include //! [0] WidgetGallery::WidgetGallery(QWidget *parent) diff --git a/examples/widgets/widgets/stylesheet/stylesheeteditor.cpp b/examples/widgets/widgets/stylesheet/stylesheeteditor.cpp index 3247fa774d..0874cc3554 100644 --- a/examples/widgets/widgets/stylesheet/stylesheeteditor.cpp +++ b/examples/widgets/widgets/stylesheet/stylesheeteditor.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "stylesheeteditor.h" +#include + StyleSheetEditor::StyleSheetEditor(QWidget *parent) : QDialog(parent) { diff --git a/examples/widgets/widgets/tablet/tabletapplication.cpp b/examples/widgets/widgets/tablet/tabletapplication.cpp index 2e5ac07c95..37be018276 100644 --- a/examples/widgets/widgets/tablet/tabletapplication.cpp +++ b/examples/widgets/widgets/tablet/tabletapplication.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "tabletapplication.h" +#include + //! [0] bool TabletApplication::event(QEvent *event) { diff --git a/examples/widgets/widgets/tetrix/main.cpp b/examples/widgets/widgets/tetrix/main.cpp index 2698190e76..92f245ca14 100644 --- a/examples/widgets/widgets/tetrix/main.cpp +++ b/examples/widgets/widgets/tetrix/main.cpp @@ -48,12 +48,10 @@ ** ****************************************************************************/ -#include - -#include - #include "tetrixwindow.h" +#include + int main(int argc, char *argv[]) { QApplication app(argc, argv); diff --git a/examples/widgets/widgets/tetrix/tetrixboard.cpp b/examples/widgets/widgets/tetrix/tetrixboard.cpp index 222ab1fb4d..b1139ca8a6 100644 --- a/examples/widgets/widgets/tetrix/tetrixboard.cpp +++ b/examples/widgets/widgets/tetrix/tetrixboard.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "tetrixboard.h" +#include + //! [0] TetrixBoard::TetrixBoard(QWidget *parent) : QFrame(parent) diff --git a/examples/widgets/widgets/tetrix/tetrixpiece.cpp b/examples/widgets/widgets/tetrix/tetrixpiece.cpp index 3d8fa86860..b1b3ca9a99 100644 --- a/examples/widgets/widgets/tetrix/tetrixpiece.cpp +++ b/examples/widgets/widgets/tetrix/tetrixpiece.cpp @@ -48,12 +48,10 @@ ** ****************************************************************************/ -#include - -#include - #include "tetrixpiece.h" +#include + //! [0] void TetrixPiece::setRandomShape() { diff --git a/examples/widgets/widgets/tetrix/tetrixwindow.h b/examples/widgets/widgets/tetrix/tetrixwindow.h index 02226ffe1c..3743d6cd2a 100644 --- a/examples/widgets/widgets/tetrix/tetrixwindow.h +++ b/examples/widgets/widgets/tetrix/tetrixwindow.h @@ -51,7 +51,6 @@ #ifndef TETRIXWINDOW_H #define TETRIXWINDOW_H -#include #include QT_BEGIN_NAMESPACE diff --git a/examples/widgets/widgets/tooltips/shapeitem.cpp b/examples/widgets/widgets/tooltips/shapeitem.cpp index 70c1cc03dc..68cc744b84 100644 --- a/examples/widgets/widgets/tooltips/shapeitem.cpp +++ b/examples/widgets/widgets/tooltips/shapeitem.cpp @@ -48,8 +48,6 @@ ** ****************************************************************************/ -#include - #include "shapeitem.h" //! [0] diff --git a/examples/widgets/widgets/tooltips/sortingbox.cpp b/examples/widgets/widgets/tooltips/sortingbox.cpp index 838083c399..685eaa7d1d 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.cpp +++ b/examples/widgets/widgets/tooltips/sortingbox.cpp @@ -48,12 +48,10 @@ ** ****************************************************************************/ -#include - -#include - #include "sortingbox.h" +#include + //! [0] SortingBox::SortingBox(QWidget *parent) : QWidget(parent) diff --git a/examples/widgets/widgets/tooltips/sortingbox.h b/examples/widgets/widgets/tooltips/sortingbox.h index 12bdeff1f6..3d0cecea2b 100644 --- a/examples/widgets/widgets/tooltips/sortingbox.h +++ b/examples/widgets/widgets/tooltips/sortingbox.h @@ -51,10 +51,10 @@ #ifndef SORTINGBOX_H #define SORTINGBOX_H -#include - #include "shapeitem.h" +#include + QT_BEGIN_NAMESPACE class QAction; class QPoint; diff --git a/examples/widgets/widgets/wiggly/dialog.cpp b/examples/widgets/widgets/wiggly/dialog.cpp index 010648eda6..a7a72b3570 100644 --- a/examples/widgets/widgets/wiggly/dialog.cpp +++ b/examples/widgets/widgets/wiggly/dialog.cpp @@ -48,12 +48,12 @@ ** ****************************************************************************/ -#include -#include - #include "dialog.h" #include "wigglywidget.h" +#include +#include + //! [0] Dialog::Dialog(QWidget *parent) : QDialog(parent) diff --git a/examples/widgets/widgets/wiggly/main.cpp b/examples/widgets/widgets/wiggly/main.cpp index bd2a50a8eb..cd888c4084 100644 --- a/examples/widgets/widgets/wiggly/main.cpp +++ b/examples/widgets/widgets/wiggly/main.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "dialog.h" +#include + int main(int argc, char *argv[]) { QApplication app(argc, argv); diff --git a/examples/widgets/widgets/wiggly/wigglywidget.cpp b/examples/widgets/widgets/wiggly/wigglywidget.cpp index 1b8f3cffad..0399fe9056 100644 --- a/examples/widgets/widgets/wiggly/wigglywidget.cpp +++ b/examples/widgets/widgets/wiggly/wigglywidget.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "wigglywidget.h" +#include + //! [0] WigglyWidget::WigglyWidget(QWidget *parent) : QWidget(parent) diff --git a/examples/widgets/widgets/windowflags/previewwindow.cpp b/examples/widgets/widgets/windowflags/previewwindow.cpp index 09e26fd7e4..8773dccb05 100644 --- a/examples/widgets/widgets/windowflags/previewwindow.cpp +++ b/examples/widgets/widgets/windowflags/previewwindow.cpp @@ -48,10 +48,10 @@ ** ****************************************************************************/ -#include - #include "previewwindow.h" +#include + //! [0] PreviewWindow::PreviewWindow(QWidget *parent) : QWidget(parent) -- cgit v1.2.3 From daee9af969a04a2919a948ba1f5d314626925a9a Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Fri, 25 Jan 2019 21:15:43 +0100 Subject: QtGui: mark obsolete QPixmapCache::find() functions as deprecated QPixmapCache::find(QString) and QPixmapCache::find(QString, QPixmap&) are deprecated since Qt4 times. Explicit mark them as deprecated so they can be removed with Qt6. Change-Id: Iaf185f69afe02203559a1c812fbb4a95c9049a1d Reviewed-by: Eirik Aavitsland --- examples/widgets/painting/shared/arthurstyle.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/painting/shared/arthurstyle.cpp b/examples/widgets/painting/shared/arthurstyle.cpp index f4fc76bda6..3df9d9a6dc 100644 --- a/examples/widgets/painting/shared/arthurstyle.cpp +++ b/examples/widgets/painting/shared/arthurstyle.cpp @@ -61,10 +61,10 @@ QPixmap cached(const QString &img) { - if (QPixmap *p = QPixmapCache::find(img)) - return *p; - QPixmap pm; + if (QPixmapCache::find(img, &pm)) + return pm; + pm = QPixmap::fromImage(QImage(img), Qt::OrderedDither | Qt::OrderedAlphaDither); if (pm.isNull()) return QPixmap(); -- cgit v1.2.3 From 5c98d15a45da1d63614b2e7181536e12d2bcb02d Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Wed, 6 Feb 2019 10:52:23 +0100 Subject: Fix some deprecation warnings in examples MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit googlesuggest.cpp:163:36: warning: ‘void QTreeWidgetItem::setTextColor(int, const QColor&)’ is deprecated: Use QTreeWidgetItem::setForeground() instead [-Wdeprecated-declarations] xbeltree.cpp:187:34: warning: ‘void QTreeWidget::setItemExpanded(const QTreeWidgetItem*, bool)’ is deprecated: Use QTreeWidgetItem::setExpanded() instead [-Wdeprecated-declarations] imageitem.cpp:114:21: warning: ‘void QGraphicsItem::setMatrix(const QMatrix&, bool)’ is deprecated: Use setTransform() instead [-Wdeprecated-declarations] xbelreader.cpp:143:48: warning: ‘void QTreeWidget::setItemExpanded(const QTreeWidgetItem*, bool)’ is deprecated: Use QTreeWidgetItem::setExpanded() instead [-Wdeprecated-declarations] xbelgenerator.cpp:103:55: warning: ‘bool QTreeWidget::isItemExpanded(const QTreeWidgetItem*) const’ is deprecated: Use QTreeWidgetItem::isExpanded() instead [-Wdeprecated-declarations] xbelwriter.cpp:90:55: warning: ‘bool QTreeWidget::isItemExpanded(const QTreeWidgetItem*) const’ is deprecated: Use QTreeWidgetItem::isExpanded() instead [-Wdeprecated-declarations] xbelhandler.cpp:97:50: warning: ‘void QTreeWidget::setItemExpanded(const QTreeWidgetItem*, bool)’ is deprecated: Use QTreeWidgetItem::setExpanded() instead [-Wdeprecated-declarations] node.cpp:180:60: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] node.cpp:181:64: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] chip.cpp:82:81: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] chip.cpp:84:40: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] chip.cpp:108:93: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] roundrectitem.cpp:65:42: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] roundrectitem.cpp:97:51: warning: ‘void QPainter::drawRoundRect(const QRectF&, int, int)’ is deprecated: Use drawRoundedRect(..., Qt::RelativeSize) instead [-Wdeprecated-declarations] roundrectitem.cpp:105:34: warning: ‘void QPainter::drawRoundRect(const QRectF&, int, int)’ is deprecated: Use drawRoundedRect(..., Qt::RelativeSize) instead [-Wdeprecated-declarations] splashitem.cpp:82:57: warning: ‘void QPainter::drawRoundRect(int, int, int, int, int, int)’ is deprecated: Use drawRoundedRect(..., Qt::RelativeSize) instead [-Wdeprecated-declarations] robot.cpp:116:53: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] robot.cpp:176:49: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] robot.cpp:200:49: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] mandelbrotwidget.cpp:120:41: warning: ‘const QMatrix& QPainter::matrix() const’ is deprecated: Use transform() instead [-Wdeprecated-declarations] composition.cpp:344:47: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] composition.cpp:346:46: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] colorswatch.cpp:89:34: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] mainwindow.cpp:81:62: warning: ‘void QTreeWidget::setItemSelected(const QTreeWidgetItem*, bool)’ is deprecated: Use QTreeWidgetItem::setSelected() instead [-Wdeprecated-declarations] puzzlewidget.cpp:172:35: warning: ‘Qt::DropAction QDrag::start(Qt::DropActions)’ is deprecated: Use QDrag::exec() instead [-Wdeprecated-declarations] spreadsheet.cpp:191:37: warning: ‘QColor QTableWidgetItem::backgroundColor() const’ is deprecated: Use QTableWidgetItem::background() instead [-Wdeprecated-declarations] spreadsheet.cpp:198:32: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] spreadsheet.cpp:203:24: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] spreadsheet.cpp:238:47: warning: ‘QColor QTableWidgetItem::backgroundColor() const’ is deprecated: Use QTableWidgetItem::background() instead [-Wdeprecated-declarations] spreadsheet.cpp:249:38: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:494:58: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:509:56: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:513:58: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:527:56: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:531:58: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:545:56: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:549:58: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:563:55: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:567:58: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:581:55: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:585:58: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] spreadsheet.cpp:599:55: warning: ‘void QTableWidgetItem::setBackgroundColor(const QColor&)’ is deprecated: Use QTableWidgetItem::setBackground() instead [-Wdeprecated-declarations] starrating.cpp:91:46: warning: ‘const QBrush& QPalette::foreground() const’ is deprecated: Use QPalette::windowText() instead [-Wdeprecated-declarations] document.cpp:341:36: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] document.cpp:342:39: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] document.cpp:343:36: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] norwegianwoodstyle.cpp:88:39: warning: ‘const QBrush& QPalette::background() const’ is deprecated: Use QPalette::window() instead [-Wdeprecated-declarations] norwegianwoodstyle.cpp:89:39: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] norwegianwoodstyle.cpp:188:52: warning: ‘const QBrush& QPalette::background() const’ is deprecated: Use QPalette::window() instead [-Wdeprecated-declarations] norwegianwoodstyle.cpp:264:56: warning: ‘const QBrush& QPalette::foreground() const’ is deprecated: Use QPalette::windowText() instead [-Wdeprecated-declarations] plugindialog.cpp:128:49: warning: ‘void QTreeWidget::setItemExpanded(const QTreeWidgetItem*, bool)’ is deprecated: Use QTreeWidgetItem::setExpanded() instead [-Wdeprecated-declarations] tetrixboard.cpp:361:74: warning: ‘const QBrush& QPalette::background() const’ is deprecated: Use QPalette::window() instead [-Wdeprecated-declarations] tetrixboard.cpp:408:32: warning: ‘QColor QColor::light(int) const’ is deprecated: Use QColor::lighter() instead [-Wdeprecated-declarations] tetrixboard.cpp:412:31: warning: ‘QColor QColor::dark(int) const’ is deprecated: Use QColor::darker() instead [-Wdeprecated-declarations] mandelbrotwidget.cpp:120:41: warning: ‘const QMatrix& QPainter::matrix() const’ is deprecated: Use transform() instead [-Wdeprecated-declarations] Change-Id: If0afabbc35ef25f127f211c11699011d4ae4ae65 Reviewed-by: Christian Ehrlicher --- examples/widgets/graphicsview/chip/chip.cpp | 6 ++-- .../widgets/graphicsview/dragdroprobot/robot.cpp | 6 ++-- .../widgets/graphicsview/elasticnodes/node.cpp | 4 +-- .../graphicsview/padnavigator/roundrectitem.cpp | 6 ++-- .../graphicsview/padnavigator/splashitem.cpp | 2 +- examples/widgets/itemviews/puzzle/puzzlewidget.cpp | 2 +- .../widgets/itemviews/spreadsheet/spreadsheet.cpp | 36 +++++++++++----------- .../widgets/itemviews/stardelegate/starrating.cpp | 2 +- .../widgets/mainwindows/mainwindow/colorswatch.cpp | 2 +- .../widgets/painting/composition/composition.cpp | 4 +-- .../tools/plugandpaint/app/plugindialog.cpp | 2 +- examples/widgets/tools/undo/document.cpp | 6 ++-- .../widgets/widgets/styles/norwegianwoodstyle.cpp | 8 ++--- examples/widgets/widgets/tetrix/tetrixboard.cpp | 6 ++-- 14 files changed, 46 insertions(+), 46 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/graphicsview/chip/chip.cpp b/examples/widgets/graphicsview/chip/chip.cpp index 443994e121..3d2bbdfcef 100644 --- a/examples/widgets/graphicsview/chip/chip.cpp +++ b/examples/widgets/graphicsview/chip/chip.cpp @@ -79,9 +79,9 @@ void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWid { Q_UNUSED(widget); - QColor fillColor = (option->state & QStyle::State_Selected) ? color.dark(150) : color; + QColor fillColor = (option->state & QStyle::State_Selected) ? color.darker(150) : color; if (option->state & QStyle::State_MouseOver) - fillColor = fillColor.light(125); + fillColor = fillColor.lighter(125); const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform()); if (lod < 0.2) { @@ -105,7 +105,7 @@ void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWid pen.setWidth(width); QBrush b = painter->brush(); - painter->setBrush(QBrush(fillColor.dark(option->state & QStyle::State_Sunken ? 120 : 100))); + painter->setBrush(QBrush(fillColor.darker(option->state & QStyle::State_Sunken ? 120 : 100))); painter->drawRect(QRect(14, 14, 79, 39)); painter->setBrush(b); diff --git a/examples/widgets/graphicsview/dragdroprobot/robot.cpp b/examples/widgets/graphicsview/dragdroprobot/robot.cpp index 38552747af..cc70366872 100644 --- a/examples/widgets/graphicsview/dragdroprobot/robot.cpp +++ b/examples/widgets/graphicsview/dragdroprobot/robot.cpp @@ -113,7 +113,7 @@ void RobotHead::paint(QPainter *painter, Q_UNUSED(option); Q_UNUSED(widget); if (pixmap.isNull()) { - painter->setBrush(dragOver ? color.light(130) : color); + painter->setBrush(dragOver ? color.lighter(130) : color); painter->drawRoundedRect(-10, -30, 20, 30, 25, 25, Qt::RelativeSize); painter->setBrush(Qt::white); painter->drawEllipse(-7, -3 - 20, 7, 7); @@ -173,7 +173,7 @@ void RobotTorso::paint(QPainter *painter, Q_UNUSED(option); Q_UNUSED(widget); - painter->setBrush(dragOver ? color.light(130) : color); + painter->setBrush(dragOver ? color.lighter(130) : color); painter->drawRoundedRect(-20, -20, 40, 60, 25, 25, Qt::RelativeSize); painter->drawEllipse(-25, -20, 20, 20); painter->drawEllipse(5, -20, 20, 20); @@ -197,7 +197,7 @@ void RobotLimb::paint(QPainter *painter, Q_UNUSED(option); Q_UNUSED(widget); - painter->setBrush(dragOver ? color.light(130) : color); + painter->setBrush(dragOver ? color.lighter(130) : color); painter->drawRoundedRect(boundingRect(), 50, 50, Qt::RelativeSize); painter->drawEllipse(-5, -5, 10, 10); } diff --git a/examples/widgets/graphicsview/elasticnodes/node.cpp b/examples/widgets/graphicsview/elasticnodes/node.cpp index d4fa3d2b4f..8d44a167fa 100644 --- a/examples/widgets/graphicsview/elasticnodes/node.cpp +++ b/examples/widgets/graphicsview/elasticnodes/node.cpp @@ -177,8 +177,8 @@ void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWid if (option->state & QStyle::State_Sunken) { gradient.setCenter(3, 3); gradient.setFocalPoint(3, 3); - gradient.setColorAt(1, QColor(Qt::yellow).light(120)); - gradient.setColorAt(0, QColor(Qt::darkYellow).light(120)); + gradient.setColorAt(1, QColor(Qt::yellow).lighter(120)); + gradient.setColorAt(0, QColor(Qt::darkYellow).lighter(120)); } else { gradient.setColorAt(0, Qt::yellow); gradient.setColorAt(1, Qt::darkYellow); diff --git a/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp b/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp index f629400a76..82205050ec 100644 --- a/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp +++ b/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp @@ -62,7 +62,7 @@ RoundRectItem::RoundRectItem(const QRectF &bounds, const QColor &color, gradient.setStart(bounds.topLeft()); gradient.setFinalStop(bounds.bottomRight()); gradient.setColorAt(0, color); - gradient.setColorAt(1, color.dark(200)); + gradient.setColorAt(1, color.darker(200)); setCacheMode(ItemCoordinateCache); } //! [0] @@ -94,7 +94,7 @@ void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opt Q_UNUSED(widget); painter->setPen(Qt::NoPen); painter->setBrush(QColor(0, 0, 0, 64)); - painter->drawRoundRect(bounds.translated(2, 2)); + painter->drawRoundedRect(bounds.translated(2, 2), 25, 25, Qt::RelativeSize); //! [3] //! [4] if (fillRect) @@ -102,7 +102,7 @@ void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opt else painter->setBrush(gradient); painter->setPen(QPen(Qt::black, 1)); - painter->drawRoundRect(bounds); + painter->drawRoundedRect(bounds, 25,25, Qt::RelativeSize); //! [4] //! [5] if (!pix.isNull()) { diff --git a/examples/widgets/graphicsview/padnavigator/splashitem.cpp b/examples/widgets/graphicsview/padnavigator/splashitem.cpp index 0c3a05dd9a..7c3dfba588 100644 --- a/examples/widgets/graphicsview/padnavigator/splashitem.cpp +++ b/examples/widgets/graphicsview/padnavigator/splashitem.cpp @@ -79,7 +79,7 @@ void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option painter->setPen(QPen(Qt::black, 2)); painter->setBrush(QColor(245, 245, 255, 220)); painter->setClipRect(boundingRect()); - painter->drawRoundRect(3, -100 + 3, 400 - 6, 250 - 6); + painter->drawRoundedRect(3, -100 + 3, 400 - 6, 250 - 6, 25, 25, Qt::RelativeSize); QRectF textRect = boundingRect().adjusted(10, 10, -10, -10); int flags = Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap; diff --git a/examples/widgets/itemviews/puzzle/puzzlewidget.cpp b/examples/widgets/itemviews/puzzle/puzzlewidget.cpp index 06968da80f..974a972306 100644 --- a/examples/widgets/itemviews/puzzle/puzzlewidget.cpp +++ b/examples/widgets/itemviews/puzzle/puzzlewidget.cpp @@ -169,7 +169,7 @@ void PuzzleWidget::mousePressEvent(QMouseEvent *event) drag->setHotSpot(event->pos() - square.topLeft()); drag->setPixmap(piece.pixmap); - if (drag->start(Qt::MoveAction) == Qt::IgnoreAction) { + if (drag->exec(Qt::MoveAction) == Qt::IgnoreAction) { pieces.insert(found, piece); update(targetSquare(event->pos())); diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp index 421b4a240c..fc7fbb872c 100644 --- a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp @@ -188,19 +188,19 @@ void SpreadSheet::updateColor(QTableWidgetItem *item) QPixmap pix(16, 16); QColor col; if (item) - col = item->backgroundColor(); + col = item->background().color(); if (!col.isValid()) col = palette().base().color(); QPainter pt(&pix); pt.fillRect(0, 0, 16, 16, col); - QColor lighter = col.light(); + QColor lighter = col.lighter(); pt.setPen(lighter); QPoint lightFrame[] = { QPoint(0, 15), QPoint(0, 0), QPoint(15, 0) }; pt.drawPolyline(lightFrame, 3); - pt.setPen(col.dark()); + pt.setPen(col.darker()); QPoint darkFrame[] = { QPoint(1, 15), QPoint(15, 15), QPoint(15, 1) }; pt.drawPolyline(darkFrame, 3); @@ -235,7 +235,7 @@ void SpreadSheet::returnPressed() void SpreadSheet::selectColor() { QTableWidgetItem *item = table->currentItem(); - QColor col = item ? item->backgroundColor() : table->palette().base().color(); + QColor col = item ? item->background().color() : table->palette().base().color(); col = QColorDialog::getColor(col, this); if (!col.isValid()) return; @@ -246,7 +246,7 @@ void SpreadSheet::selectColor() for (QTableWidgetItem *i : selected) { if (i) - i->setBackgroundColor(col); + i->setBackground(col); } updateColor(table->currentItem()); @@ -485,13 +485,13 @@ void SpreadSheet::setupContextMenu() void SpreadSheet::setupContents() { - QColor titleBackground(Qt::lightGray); + QBrush titleBackground(Qt::lightGray); QFont titleFont = table->font(); titleFont.setBold(true); // column 0 table->setItem(0, 0, new SpreadSheetItem("Item")); - table->item(0, 0)->setBackgroundColor(titleBackground); + table->item(0, 0)->setBackground(titleBackground); table->item(0, 0)->setToolTip("This column shows the purchased item/service"); table->item(0, 0)->setFont(titleFont); @@ -506,11 +506,11 @@ void SpreadSheet::setupContents() table->setItem(9, 0, new SpreadSheetItem("Total:")); table->item(9, 0)->setFont(titleFont); - table->item(9, 0)->setBackgroundColor(Qt::lightGray); + table->item(9, 0)->setBackground(titleBackground); // column 1 table->setItem(0, 1, new SpreadSheetItem("Date")); - table->item(0, 1)->setBackgroundColor(titleBackground); + table->item(0, 1)->setBackground(titleBackground); table->item(0, 1)->setToolTip("This column shows the purchase date, double click to change"); table->item(0, 1)->setFont(titleFont); @@ -524,11 +524,11 @@ void SpreadSheet::setupContents() table->setItem(8, 1, new SpreadSheetItem("18/6/2006")); table->setItem(9, 1, new SpreadSheetItem()); - table->item(9, 1)->setBackgroundColor(Qt::lightGray); + table->item(9, 1)->setBackground(titleBackground); // column 2 table->setItem(0, 2, new SpreadSheetItem("Price")); - table->item(0, 2)->setBackgroundColor(titleBackground); + table->item(0, 2)->setBackground(titleBackground); table->item(0, 2)->setToolTip("This column shows the price of the purchase"); table->item(0, 2)->setFont(titleFont); @@ -542,11 +542,11 @@ void SpreadSheet::setupContents() table->setItem(8, 2, new SpreadSheetItem("1240")); table->setItem(9, 2, new SpreadSheetItem()); - table->item(9, 2)->setBackgroundColor(Qt::lightGray); + table->item(9, 2)->setBackground(Qt::lightGray); // column 3 table->setItem(0, 3, new SpreadSheetItem("Currency")); - table->item(0, 3)->setBackgroundColor(titleBackground); + table->item(0, 3)->setBackground(titleBackground); table->item(0, 3)->setToolTip("This column shows the currency"); table->item(0, 3)->setFont(titleFont); @@ -560,11 +560,11 @@ void SpreadSheet::setupContents() table->setItem(8, 3, new SpreadSheetItem("USD")); table->setItem(9, 3, new SpreadSheetItem()); - table->item(9,3)->setBackgroundColor(Qt::lightGray); + table->item(9, 3)->setBackground(Qt::lightGray); // column 4 table->setItem(0, 4, new SpreadSheetItem("Ex. Rate")); - table->item(0, 4)->setBackgroundColor(titleBackground); + table->item(0, 4)->setBackground(titleBackground); table->item(0, 4)->setToolTip("This column shows the exchange rate to NOK"); table->item(0, 4)->setFont(titleFont); @@ -578,11 +578,11 @@ void SpreadSheet::setupContents() table->setItem(8, 4, new SpreadSheetItem("7")); table->setItem(9, 4, new SpreadSheetItem()); - table->item(9,4)->setBackgroundColor(Qt::lightGray); + table->item(9, 4)->setBackground(titleBackground); // column 5 table->setItem(0, 5, new SpreadSheetItem("NOK")); - table->item(0, 5)->setBackgroundColor(titleBackground); + table->item(0, 5)->setBackground(titleBackground); table->item(0, 5)->setToolTip("This column shows the expenses in NOK"); table->item(0, 5)->setFont(titleFont); @@ -596,7 +596,7 @@ void SpreadSheet::setupContents() table->setItem(8, 5, new SpreadSheetItem("* C9 E9")); table->setItem(9, 5, new SpreadSheetItem("sum F2 F9")); - table->item(9,5)->setBackgroundColor(Qt::lightGray); + table->item(9, 5)->setBackground(titleBackground); } const char *htmlText = diff --git a/examples/widgets/itemviews/stardelegate/starrating.cpp b/examples/widgets/itemviews/stardelegate/starrating.cpp index 15e14965e3..75f0bd9cf7 100644 --- a/examples/widgets/itemviews/stardelegate/starrating.cpp +++ b/examples/widgets/itemviews/stardelegate/starrating.cpp @@ -88,7 +88,7 @@ void StarRating::paint(QPainter *painter, const QRect &rect, painter->setPen(Qt::NoPen); painter->setBrush(mode == EditMode::Editable ? palette.highlight() : - palette.foreground()); + palette.windowText()); const int yOffset = (rect.height() - PaintingScaleFactor) / 2; painter->translate(rect.x(), rect.y() + yOffset); diff --git a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp index 4e4c15ccaf..5662518ddc 100644 --- a/examples/widgets/mainwindows/mainwindow/colorswatch.cpp +++ b/examples/widgets/mainwindows/mainwindow/colorswatch.cpp @@ -86,7 +86,7 @@ QColor bgColorForName(const QString &name) return QColor("#D8D8F1"); if (name == "Yellow") return QColor("#F1F0D8"); - return QColor(name).light(110); + return QColor(name).lighter(110); } QColor fgColorForName(const QString &name) diff --git a/examples/widgets/painting/composition/composition.cpp b/examples/widgets/painting/composition/composition.cpp index 96088cca4a..9bd71735a0 100644 --- a/examples/widgets/painting/composition/composition.cpp +++ b/examples/widgets/painting/composition/composition.cpp @@ -341,9 +341,9 @@ void CompositionRenderer::drawSource(QPainter &p) QRectF circle_rect = rectangle_around(m_circle_pos); QColor color = QColor::fromHsvF(m_circle_hue / 360.0, 1, 1, m_circle_alpha / 255.0); QLinearGradient circle_gradient(circle_rect.topLeft(), circle_rect.bottomRight()); - circle_gradient.setColorAt(0, color.light()); + circle_gradient.setColorAt(0, color.lighter()); circle_gradient.setColorAt(0.5, color); - circle_gradient.setColorAt(1, color.dark()); + circle_gradient.setColorAt(1, color.darker()); p.setBrush(circle_gradient); p.drawEllipse(circle_rect); diff --git a/examples/widgets/tools/plugandpaint/app/plugindialog.cpp b/examples/widgets/tools/plugandpaint/app/plugindialog.cpp index af5828f67e..84bd364b41 100644 --- a/examples/widgets/tools/plugandpaint/app/plugindialog.cpp +++ b/examples/widgets/tools/plugandpaint/app/plugindialog.cpp @@ -125,7 +125,7 @@ void PluginDialog::populateTreeWidget(QObject *plugin, const QString &text) { auto pluginItem = new QTreeWidgetItem(treeWidget); pluginItem->setText(0, text); - treeWidget->setItemExpanded(pluginItem, true); + pluginItem->setExpanded(true); QFont boldFont = pluginItem->font(0); boldFont.setBold(true); diff --git a/examples/widgets/tools/undo/document.cpp b/examples/widgets/tools/undo/document.cpp index 212656721e..8935f98a7a 100644 --- a/examples/widgets/tools/undo/document.cpp +++ b/examples/widgets/tools/undo/document.cpp @@ -338,9 +338,9 @@ static QGradient gradient(const QColor &color, const QRect &rect) QColor c = color; c.setAlpha(160); QLinearGradient result(rect.topLeft(), rect.bottomRight()); - result.setColorAt(0, c.dark(150)); - result.setColorAt(0.5, c.light(200)); - result.setColorAt(1, c.dark(150)); + result.setColorAt(0, c.darker(150)); + result.setColorAt(0.5, c.lighter(200)); + result.setColorAt(1, c.darker(150)); return result; } diff --git a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp index b334ca97cb..1d7ef2637b 100644 --- a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp +++ b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp @@ -85,8 +85,8 @@ void NorwegianWoodStyle::polish(QPalette &palette) setTexture(palette, QPalette::Mid, midImage); setTexture(palette, QPalette::Window, backgroundImage); - QBrush brush = palette.background(); - brush.setColor(brush.color().dark()); + QBrush brush = palette.window(); + brush.setColor(brush.color().darker()); palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush); palette.setBrush(QPalette::Disabled, QPalette::Text, brush); @@ -185,7 +185,7 @@ void NorwegianWoodStyle::drawPrimitive(PrimitiveElement element, qstyleoption_cast(option); if (buttonOption && (buttonOption->features & QStyleOptionButton::Flat)) { - brush = option->palette.background(); + brush = option->palette.window(); darker = (option->state & (State_Sunken | State_On)); } else { if (option->state & (State_Sunken | State_On)) { @@ -261,7 +261,7 @@ void NorwegianWoodStyle::drawPrimitive(PrimitiveElement element, painter->setPen(bottomPen); painter->drawPath(roundRect); - painter->setPen(option->palette.foreground().color()); + painter->setPen(option->palette.windowText().color()); painter->setClipping(false); painter->drawPath(roundRect); diff --git a/examples/widgets/widgets/tetrix/tetrixboard.cpp b/examples/widgets/widgets/tetrix/tetrixboard.cpp index b1139ca8a6..ef3ac4fc38 100644 --- a/examples/widgets/widgets/tetrix/tetrixboard.cpp +++ b/examples/widgets/widgets/tetrix/tetrixboard.cpp @@ -358,7 +358,7 @@ void TetrixBoard::showNextPiece() QPixmap pixmap(dx * squareWidth(), dy * squareHeight()); QPainter painter(&pixmap); - painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background()); + painter.fillRect(pixmap.rect(), nextPieceLabel->palette().window()); for (int i = 0; i < 4; ++i) { int x = nextPiece.x(i) - nextPiece.minX(); @@ -405,11 +405,11 @@ void TetrixBoard::drawSquare(QPainter &painter, int x, int y, TetrixShape shape) painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2, color); - painter.setPen(color.light()); + painter.setPen(color.lighter()); painter.drawLine(x, y + squareHeight() - 1, x, y); painter.drawLine(x, y, x + squareWidth() - 1, y); - painter.setPen(color.dark()); + painter.setPen(color.darker()); painter.drawLine(x + 1, y + squareHeight() - 1, x + squareWidth() - 1, y + squareHeight() - 1); painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1, -- cgit v1.2.3 From 90a8de656fe689b6aa856e70e2d22de6630ea855 Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Tue, 26 Jun 2018 17:12:02 +0200 Subject: Long live QColorSpace and friends Adds QColorSpace and QColorTransform classes, and parsing of a common subset of ICC profiles found in images, and also parses the ICC profiles in PNG and JPEGs. For backwards compatibility no automatic color handling is done by this patch. [ChangeLog][QtGui] A QColorSpace class has been added, and color spaces are now parsed from PNG and JPEG images. No automatic color space conversion is done however, and applications must request it. Change-Id: Ic09935f84640a716467fa3a9ed1e73c02daf3675 Reviewed-by: Eirik Aavitsland --- examples/widgets/widgets/imageviewer/imageviewer.cpp | 2 ++ 1 file changed, 2 insertions(+) (limited to 'examples/widgets') diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp index fed551dade..2fc8ff63de 100644 --- a/examples/widgets/widgets/imageviewer/imageviewer.cpp +++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp @@ -106,6 +106,8 @@ bool ImageViewer::loadFile(const QString &fileName) void ImageViewer::setImage(const QImage &newImage) { image = newImage; + if (image.colorSpace().isValid()) + image.convertToColorSpace(QColorSpace::SRgb); imageLabel->setPixmap(QPixmap::fromImage(image)); //! [4] scaleFactor = 1.0; -- cgit v1.2.3 From 8cba096c2aa181b93887fa6f6086dee689dbf5ca Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sat, 9 Feb 2019 18:43:05 +0100 Subject: QtBase: compile examples with QT_DISABLE_DEPRECATED_BEFORE=0x050d00 Replace deprecated functions to be able to compile examples with QT_DISABLE_DEPRECATED_BEFORE=0x050d00 Change-Id: If6b8de31f526320d6a0e2a20bb5f8e26c77f2353 Reviewed-by: Friedemann Kleint --- examples/widgets/dialogs/extension/finddialog.cpp | 2 +- examples/widgets/layouts/borderlayout/borderlayout.cpp | 4 ++-- examples/widgets/layouts/borderlayout/borderlayout.h | 2 +- examples/widgets/layouts/flowlayout/flowlayout.cpp | 3 ++- examples/widgets/mainwindows/menus/mainwindow.cpp | 2 +- examples/widgets/painting/deform/pathdeform.cpp | 4 ++-- examples/widgets/painting/fontsampler/mainwindow.cpp | 2 +- examples/widgets/painting/gradients/gradients.cpp | 2 +- examples/widgets/painting/pathstroke/pathstroke.cpp | 14 +++++++------- examples/widgets/painting/shared/arthurstyle.cpp | 4 ++-- examples/widgets/statemachine/trafficlight/main.cpp | 6 +++--- .../tools/regularexpression/regularexpressiondialog.cpp | 4 ++-- examples/widgets/widgets/styles/widgetgallery.cpp | 4 ++-- 13 files changed, 27 insertions(+), 26 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/dialogs/extension/finddialog.cpp b/examples/widgets/dialogs/extension/finddialog.cpp index 1321155f00..10a4ae1ac0 100644 --- a/examples/widgets/dialogs/extension/finddialog.cpp +++ b/examples/widgets/dialogs/extension/finddialog.cpp @@ -91,7 +91,7 @@ FindDialog::FindDialog(QWidget *parent) connect(moreButton, &QAbstractButton::toggled, extension, &QWidget::setVisible); QVBoxLayout *extensionLayout = new QVBoxLayout; - extensionLayout->setMargin(0); + extensionLayout->setContentsMargins(QMargins()); extensionLayout->addWidget(wholeWordsCheckBox); extensionLayout->addWidget(backwardCheckBox); extensionLayout->addWidget(searchSelectionCheckBox); diff --git a/examples/widgets/layouts/borderlayout/borderlayout.cpp b/examples/widgets/layouts/borderlayout/borderlayout.cpp index c929d3b2a4..b8ddd3af83 100644 --- a/examples/widgets/layouts/borderlayout/borderlayout.cpp +++ b/examples/widgets/layouts/borderlayout/borderlayout.cpp @@ -50,10 +50,10 @@ #include "borderlayout.h" -BorderLayout::BorderLayout(QWidget *parent, int margin, int spacing) +BorderLayout::BorderLayout(QWidget *parent, const QMargins &margins, int spacing) : QLayout(parent) { - setMargin(margin); + setContentsMargins(margins); setSpacing(spacing); } diff --git a/examples/widgets/layouts/borderlayout/borderlayout.h b/examples/widgets/layouts/borderlayout/borderlayout.h index 4c0c01f90b..58d1aa394d 100644 --- a/examples/widgets/layouts/borderlayout/borderlayout.h +++ b/examples/widgets/layouts/borderlayout/borderlayout.h @@ -59,7 +59,7 @@ class BorderLayout : public QLayout public: enum Position { West, North, South, East, Center }; - explicit BorderLayout(QWidget *parent, int margin = 0, int spacing = -1); + explicit BorderLayout(QWidget *parent, const QMargins &margins = QMargins(), int spacing = -1); BorderLayout(int spacing = -1); ~BorderLayout(); diff --git a/examples/widgets/layouts/flowlayout/flowlayout.cpp b/examples/widgets/layouts/flowlayout/flowlayout.cpp index 53613b8b20..5c59ae025c 100644 --- a/examples/widgets/layouts/flowlayout/flowlayout.cpp +++ b/examples/widgets/layouts/flowlayout/flowlayout.cpp @@ -158,7 +158,8 @@ QSize FlowLayout::minimumSize() const for (const QLayoutItem *item : qAsConst(itemList)) size = size.expandedTo(item->minimumSize()); - size += QSize(2*margin(), 2*margin()); + const QMargins margins = contentsMargins(); + size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom()); return size; } //! [8] diff --git a/examples/widgets/mainwindows/menus/mainwindow.cpp b/examples/widgets/mainwindows/menus/mainwindow.cpp index 600b04fdb2..c6aba8be83 100644 --- a/examples/widgets/mainwindows/menus/mainwindow.cpp +++ b/examples/widgets/mainwindows/menus/mainwindow.cpp @@ -72,7 +72,7 @@ MainWindow::MainWindow() bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout *layout = new QVBoxLayout; - layout->setMargin(5); + layout->setContentsMargins(5, 5, 5, 5); layout->addWidget(topFiller); layout->addWidget(infoLabel); layout->addWidget(bottomFiller); diff --git a/examples/widgets/painting/deform/pathdeform.cpp b/examples/widgets/painting/deform/pathdeform.cpp index 0eda76a831..64e81f8cab 100644 --- a/examples/widgets/painting/deform/pathdeform.cpp +++ b/examples/widgets/painting/deform/pathdeform.cpp @@ -150,7 +150,7 @@ void PathDeformControls::layoutForDesktop() QVBoxLayout * mainLayout = new QVBoxLayout(this); mainLayout->addWidget(mainGroup); - mainLayout->setMargin(0); + mainLayout->setContentsMargins(QMargins()); connect(radiusSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setRadius); connect(deformSlider, &QAbstractSlider::valueChanged, m_renderer, &PathDeformRenderer::setIntensity); @@ -211,7 +211,7 @@ void PathDeformControls::layoutForSmallScreen() QGridLayout *mainGroupLayout = new QGridLayout(mainGroup); - mainGroupLayout->setMargin(0); + mainGroupLayout->setContentsMargins(QMargins()); mainGroupLayout->addWidget(radiusLabel, 0, 0, Qt::AlignRight); mainGroupLayout->addWidget(radiusSlider, 0, 1); mainGroupLayout->addWidget(deformLabel, 1, 0, Qt::AlignRight); diff --git a/examples/widgets/painting/fontsampler/mainwindow.cpp b/examples/widgets/painting/fontsampler/mainwindow.cpp index a464eee3ff..b3304b4b6d 100644 --- a/examples/widgets/painting/fontsampler/mainwindow.cpp +++ b/examples/widgets/painting/fontsampler/mainwindow.cpp @@ -78,7 +78,7 @@ MainWindow::MainWindow(QWidget *parent) connect(fontTree, &QTreeWidget::itemChanged, this, &MainWindow::updateStyles); - fontTree->setItemSelected(fontTree->topLevelItem(0), true); + fontTree->topLevelItem(0)->setSelected(true); showFont(fontTree->topLevelItem(0)); } diff --git a/examples/widgets/painting/gradients/gradients.cpp b/examples/widgets/painting/gradients/gradients.cpp index fd6eaeb0d9..7abaef771b 100644 --- a/examples/widgets/painting/gradients/gradients.cpp +++ b/examples/widgets/painting/gradients/gradients.cpp @@ -180,7 +180,7 @@ GradientEditor::GradientEditor(QWidget *parent) { QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setSpacing(1); - vbox->setMargin(1); + vbox->setContentsMargins(1, 1, 1, 1); m_red_shade = new ShadeWidget(ShadeWidget::RedShade, this); m_green_shade = new ShadeWidget(ShadeWidget::GreenShade, this); diff --git a/examples/widgets/painting/pathstroke/pathstroke.cpp b/examples/widgets/painting/pathstroke/pathstroke.cpp index cad0b8732c..03e55bb2a2 100644 --- a/examples/widgets/painting/pathstroke/pathstroke.cpp +++ b/examples/widgets/painting/pathstroke/pathstroke.cpp @@ -227,11 +227,11 @@ void PathStrokeControls::layoutForDesktop() penWidthLayout->addWidget(penWidth); QVBoxLayout * mainLayout = new QVBoxLayout(this); - mainLayout->setMargin(0); + mainLayout->setContentsMargins(QMargins()); mainLayout->addWidget(mainGroup); QVBoxLayout *mainGroupLayout = new QVBoxLayout(mainGroup); - mainGroupLayout->setMargin(3); + mainGroupLayout->setContentsMargins(3, 3, 3, 3); mainGroupLayout->addWidget(m_capGroup); mainGroupLayout->addWidget(m_joinGroup); mainGroupLayout->addWidget(m_styleGroup); @@ -270,10 +270,10 @@ void PathStrokeControls::layoutForSmallScreens() { createCommonControls(this); - m_capGroup->layout()->setMargin(0); - m_joinGroup->layout()->setMargin(0); - m_styleGroup->layout()->setMargin(0); - m_pathModeGroup->layout()->setMargin(0); + m_capGroup->layout()->setContentsMargins(QMargins()); + m_joinGroup->layout()->setContentsMargins(QMargins()); + m_styleGroup->layout()->setContentsMargins(QMargins()); + m_pathModeGroup->layout()->setContentsMargins(QMargins()); QPushButton* okBtn = new QPushButton(tr("OK"), this); okBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -313,7 +313,7 @@ void PathStrokeControls::layoutForSmallScreens() rightLayout->addWidget(m_pathModeGroup); QGridLayout *mainLayout = new QGridLayout(this); - mainLayout->setMargin(0); + mainLayout->setContentsMargins(QMargins()); // Add spacers around the form items so we don't look stupid at higher resolutions mainLayout->addItem(new QSpacerItem(0,0), 0, 0, 1, 4); diff --git a/examples/widgets/painting/shared/arthurstyle.cpp b/examples/widgets/painting/shared/arthurstyle.cpp index 3df9d9a6dc..3fc461bbd2 100644 --- a/examples/widgets/painting/shared/arthurstyle.cpp +++ b/examples/widgets/painting/shared/arthurstyle.cpp @@ -443,9 +443,9 @@ void ArthurStyle::polish(QWidget *widget) if (widget->layout() && qobject_cast(widget)) { if (widget->findChildren().size() == 0) { widget->layout()->setSpacing(0); - widget->layout()->setMargin(12); + widget->layout()->setContentsMargins(12, 12, 12, 12); } else { - widget->layout()->setMargin(13); + widget->layout()->setContentsMargins(13, 13, 13, 13); } } diff --git a/examples/widgets/statemachine/trafficlight/main.cpp b/examples/widgets/statemachine/trafficlight/main.cpp index b348d4f65d..1a7050c28d 100644 --- a/examples/widgets/statemachine/trafficlight/main.cpp +++ b/examples/widgets/statemachine/trafficlight/main.cpp @@ -146,13 +146,13 @@ QState *createLightState(LightWidget *light, int duration, QState *parent = 0) class TrafficLight : public QWidget { public: - TrafficLight(QWidget *parent = 0) + TrafficLight(QWidget *parent = nullptr) : QWidget(parent) { QVBoxLayout *vbox = new QVBoxLayout(this); - TrafficLightWidget *widget = new TrafficLightWidget(); + TrafficLightWidget *widget = new TrafficLightWidget; vbox->addWidget(widget); - vbox->setMargin(0); + vbox->setContentsMargins(QMargins()); QStateMachine *machine = new QStateMachine(this); QState *redGoingYellow = createLightState(widget->redLight(), 3000); diff --git a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp index 8fbf143cbd..ea3cb00a02 100644 --- a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp +++ b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp @@ -376,7 +376,7 @@ QWidget *RegularExpressionDialog::setupLeftUi() QFormLayout *layout = new QFormLayout(container); layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - layout->setMargin(0); + layout->setContentsMargins(QMargins()); QLabel *regexpAndSubjectLabel = new QLabel(tr("

Regular expression and text input

")); layout->addRow(regexpAndSubjectLabel); @@ -448,7 +448,7 @@ QWidget *RegularExpressionDialog::setupRightUi() QFormLayout *layout = new QFormLayout(container); layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - layout->setMargin(0); + layout->setContentsMargins(QMargins()); QLabel *matchInfoLabel = new QLabel(tr("

Match information

")); layout->addRow(matchInfoLabel); diff --git a/examples/widgets/widgets/styles/widgetgallery.cpp b/examples/widgets/widgets/styles/widgetgallery.cpp index 7f4b7f39d4..f0a0336a94 100644 --- a/examples/widgets/widgets/styles/widgetgallery.cpp +++ b/examples/widgets/widgets/styles/widgetgallery.cpp @@ -212,7 +212,7 @@ void WidgetGallery::createBottomLeftTabWidget() tableWidget = new QTableWidget(10, 10); QHBoxLayout *tab1hbox = new QHBoxLayout; - tab1hbox->setMargin(5); + tab1hbox->setContentsMargins(5,5, 5, 5); tab1hbox->addWidget(tableWidget); tab1->setLayout(tab1hbox); @@ -227,7 +227,7 @@ void WidgetGallery::createBottomLeftTabWidget() "How I wonder what you are!\n")); QHBoxLayout *tab2hbox = new QHBoxLayout; - tab2hbox->setMargin(5); + tab2hbox->setContentsMargins(5, 5, 5, 5); tab2hbox->addWidget(textEdit); tab2->setLayout(tab2hbox); -- cgit v1.2.3 From 8fe36801930872ef4a57e2ff7d7f935de12a33e9 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Fri, 1 Feb 2019 15:16:00 +0100 Subject: Add cmdline feature to qmake [ChangeLog][qmake] A new feature "cmdline" was added that implies "CONFIG += console" and "CONFIG -= app_bundle". Task-number: QTBUG-27079 Change-Id: I6e52b07c9341c904bb1424fc717057432f9360e1 Reviewed-by: Oswald Buddenhagen --- examples/widgets/statemachine/factorial/factorial.pro | 3 +-- examples/widgets/statemachine/pingpong/pingpong.pro | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/statemachine/factorial/factorial.pro b/examples/widgets/statemachine/factorial/factorial.pro index f200c738ba..bf285acf4d 100644 --- a/examples/widgets/statemachine/factorial/factorial.pro +++ b/examples/widgets/statemachine/factorial/factorial.pro @@ -1,6 +1,5 @@ QT = core -win32: CONFIG += console -mac:CONFIG -= app_bundle +CONFIG += cmdline SOURCES += main.cpp diff --git a/examples/widgets/statemachine/pingpong/pingpong.pro b/examples/widgets/statemachine/pingpong/pingpong.pro index 7cc27a13f5..18dee0400d 100644 --- a/examples/widgets/statemachine/pingpong/pingpong.pro +++ b/examples/widgets/statemachine/pingpong/pingpong.pro @@ -1,6 +1,5 @@ QT = core -win32: CONFIG += console -mac:CONFIG -= app_bundle +CONFIG += cmdline SOURCES = main.cpp -- cgit v1.2.3 From d8ac4b40b5acb5582b1491f48f3d3c2cfc044666 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 3 Mar 2019 19:31:26 +0100 Subject: Examples: replace deprecated QComboBox functions Replace the deprecated currentIndexChanged(QString) and activated(QString) with the new currentTextChanged() and textActivated() functions Change-Id: I8616354fa06cc63dce6f5cfef0902f4b55981043 Reviewed-by: Friedemann Kleint --- examples/widgets/graphicsview/diagramscene/mainwindow.cpp | 4 ++-- examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp | 2 +- examples/widgets/richtext/textedit/textedit.cpp | 4 ++-- examples/widgets/widgets/charactermap/mainwindow.cpp | 4 ++-- examples/widgets/widgets/spinboxes/window.cpp | 2 +- examples/widgets/widgets/styles/widgetgallery.cpp | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp index 07f92f61c1..3327d4d5df 100644 --- a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp +++ b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp @@ -473,7 +473,7 @@ void MainWindow::createToolbars() fontSizeCombo->addItem(QString().setNum(i)); QIntValidator *validator = new QIntValidator(2, 64, this); fontSizeCombo->setValidator(validator); - connect(fontSizeCombo, QOverload::of(&QComboBox::currentIndexChanged), + connect(fontSizeCombo, &QComboBox::currentTextChanged, this, &MainWindow::fontSizeChanged); fontColorToolButton = new QToolButton; @@ -536,7 +536,7 @@ void MainWindow::createToolbars() scales << tr("50%") << tr("75%") << tr("100%") << tr("125%") << tr("150%"); sceneScaleCombo->addItems(scales); sceneScaleCombo->setCurrentIndex(2); - connect(sceneScaleCombo, QOverload::of(&QComboBox::currentIndexChanged), + connect(sceneScaleCombo, &QComboBox::currentTextChanged, this, &MainWindow::sceneScaleChanged); pointerToolbar = addToolBar(tr("Pointer type")); diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp index 0c831360cf..9fa24fcd17 100644 --- a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp @@ -73,7 +73,7 @@ EmbeddedDialog::EmbeddedDialog(QWidget *parent) this, &EmbeddedDialog::spacingChanged); connect(ui->fontComboBox, &QFontComboBox::currentFontChanged, this, &EmbeddedDialog::fontChanged); - connect(ui->style, QOverload::of(&QComboBox::activated), + connect(ui->style, &QComboBox::textActivated, this, &EmbeddedDialog::styleChanged); } diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp index 00ea0325dc..3ad9f48b67 100644 --- a/examples/widgets/richtext/textedit/textedit.cpp +++ b/examples/widgets/richtext/textedit/textedit.cpp @@ -369,7 +369,7 @@ void TextEdit::setupTextActions() comboFont = new QFontComboBox(tb); tb->addWidget(comboFont); - connect(comboFont, QOverload::of(&QComboBox::activated), this, &TextEdit::textFamily); + connect(comboFont, &QComboBox::textActivated, this, &TextEdit::textFamily); comboSize = new QComboBox(tb); comboSize->setObjectName("comboSize"); @@ -381,7 +381,7 @@ void TextEdit::setupTextActions() comboSize->addItem(QString::number(size)); comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize())); - connect(comboSize, QOverload::of(&QComboBox::activated), this, &TextEdit::textSize); + connect(comboSize, &QComboBox::textActivated, this, &TextEdit::textSize); } bool TextEdit::load(const QString &f) diff --git a/examples/widgets/widgets/charactermap/mainwindow.cpp b/examples/widgets/widgets/charactermap/mainwindow.cpp index e84ded5afb..77aad145e7 100644 --- a/examples/widgets/widgets/charactermap/mainwindow.cpp +++ b/examples/widgets/widgets/charactermap/mainwindow.cpp @@ -114,9 +114,9 @@ MainWindow::MainWindow(QWidget *parent) this, &MainWindow::findSizes); connect(fontCombo, &QFontComboBox::currentFontChanged, characterWidget, &CharacterWidget::updateFont); - connect(sizeCombo, QOverload::of(&QComboBox::currentIndexChanged), + connect(sizeCombo, &QComboBox::currentTextChanged, characterWidget, &CharacterWidget::updateSize); - connect(styleCombo, QOverload::of(&QComboBox::currentIndexChanged), + connect(styleCombo, &QComboBox::currentTextChanged, characterWidget, &CharacterWidget::updateStyle); //! [4] //! [5] connect(characterWidget, &CharacterWidget::characterSelected, diff --git a/examples/widgets/widgets/spinboxes/window.cpp b/examples/widgets/widgets/spinboxes/window.cpp index fd7c5b527e..82e19527a7 100644 --- a/examples/widgets/widgets/spinboxes/window.cpp +++ b/examples/widgets/widgets/spinboxes/window.cpp @@ -176,7 +176,7 @@ void Window::createDateTimeEdits() formatComboBox->addItem("hh:mm ap"); //! [9] //! [10] - connect(formatComboBox, QOverload::of(&QComboBox::activated), + connect(formatComboBox, &QComboBox::textActivated, this, &Window::setFormatString); //! [10] diff --git a/examples/widgets/widgets/styles/widgetgallery.cpp b/examples/widgets/widgets/styles/widgetgallery.cpp index f0a0336a94..34c010df74 100644 --- a/examples/widgets/widgets/styles/widgetgallery.cpp +++ b/examples/widgets/widgets/styles/widgetgallery.cpp @@ -79,7 +79,7 @@ WidgetGallery::WidgetGallery(QWidget *parent) //! [0] //! [1] - connect(styleComboBox, QOverload::of(&QComboBox::activated), + connect(styleComboBox, &QComboBox::textActivated, //! [1] //! [2] this, &WidgetGallery::changeStyle); connect(useStylePaletteCheckBox, &QCheckBox::toggled, -- cgit v1.2.3 From 10ec683a968486df68c013f456df4d1798ea27d3 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 3 Mar 2019 12:06:58 +0100 Subject: QLineF: mark angle(const QLineF&) as deprecated QLineF::angle(const QLineF&) was deprecated during Qt4 times but not decorated with QT_DEPRECATED_X. Add this so it can be removed with Qt6 Change-Id: I8950b646cc5fa8206e47bdd16647d17d615f6c6a Reviewed-by: Lars Knoll --- examples/widgets/painting/affine/xform.cpp | 5 +---- examples/widgets/painting/gradients/gradients.cpp | 4 +--- 2 files changed, 2 insertions(+), 7 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/painting/affine/xform.cpp b/examples/widgets/painting/affine/xform.cpp index dc01acf453..482e0f3268 100644 --- a/examples/widgets/painting/affine/xform.cpp +++ b/examples/widgets/painting/affine/xform.cpp @@ -160,10 +160,7 @@ void XFormView::updateCtrlPoints(const QPolygonF &points) ctrlPoints = points; QLineF line(ctrlPoints.at(0), ctrlPoints.at(1)); - m_rotation = line.angle(QLineF(0, 0, 1, 0)); - if (line.dy() < 0) - m_rotation = 360 - m_rotation; - + m_rotation = 360 - QLineF(0, 0, 1, 0).angleTo(line); if (trans.isNull()) emit rotationChanged(int(m_rotation*10)); } diff --git a/examples/widgets/painting/gradients/gradients.cpp b/examples/widgets/painting/gradients/gradients.cpp index 7abaef771b..8df45be8d9 100644 --- a/examples/widgets/painting/gradients/gradients.cpp +++ b/examples/widgets/painting/gradients/gradients.cpp @@ -564,9 +564,7 @@ void GradientRenderer::paint(QPainter *p) } else { QLineF l(pts.at(0), pts.at(1)); - qreal angle = l.angle(QLineF(0, 0, 1, 0)); - if (l.dy() > 0) - angle = 360 - angle; + qreal angle = QLineF(0, 0, 1, 0).angleTo(l); g = QConicalGradient(pts.at(0), angle); } -- cgit v1.2.3 From 50f3f8f6bb8f5482c713480fad80421760184216 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Wed, 13 Mar 2019 08:34:01 +0100 Subject: Use High DPI pixmaps in prominent examples and tests Set AA_UseHighDpiPixmaps. Task-number: QTBUG-52622 Change-Id: Ic4373a9c94952f50bc1ad36bcc0dec850efc124a Reviewed-by: Robert Loehning Reviewed-by: Richard Moe Gustavsen --- examples/widgets/desktop/systray/main.cpp | 2 ++ examples/widgets/dialogs/classwizard/main.cpp | 2 ++ examples/widgets/dialogs/licensewizard/main.cpp | 2 ++ examples/widgets/dialogs/standarddialogs/main.cpp | 1 + examples/widgets/dialogs/trivialwizard/trivialwizard.cpp | 2 ++ 5 files changed, 9 insertions(+) (limited to 'examples/widgets') diff --git a/examples/widgets/desktop/systray/main.cpp b/examples/widgets/desktop/systray/main.cpp index 49b0e10412..d981415b44 100644 --- a/examples/widgets/desktop/systray/main.cpp +++ b/examples/widgets/desktop/systray/main.cpp @@ -59,6 +59,8 @@ int main(int argc, char *argv[]) { Q_INIT_RESOURCE(systray); + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc, argv); if (!QSystemTrayIcon::isSystemTrayAvailable()) { diff --git a/examples/widgets/dialogs/classwizard/main.cpp b/examples/widgets/dialogs/classwizard/main.cpp index 72eb1ae6ec..03ffe97a23 100644 --- a/examples/widgets/dialogs/classwizard/main.cpp +++ b/examples/widgets/dialogs/classwizard/main.cpp @@ -59,6 +59,8 @@ int main(int argc, char *argv[]) { Q_INIT_RESOURCE(classwizard); + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc, argv); #ifndef QT_NO_TRANSLATION diff --git a/examples/widgets/dialogs/licensewizard/main.cpp b/examples/widgets/dialogs/licensewizard/main.cpp index 025b79243c..ed46e792d0 100644 --- a/examples/widgets/dialogs/licensewizard/main.cpp +++ b/examples/widgets/dialogs/licensewizard/main.cpp @@ -59,6 +59,8 @@ int main(int argc, char *argv[]) { Q_INIT_RESOURCE(licensewizard); + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc, argv); #ifndef QT_NO_TRANSLATION diff --git a/examples/widgets/dialogs/standarddialogs/main.cpp b/examples/widgets/dialogs/standarddialogs/main.cpp index 150d07318e..a0cded4f47 100644 --- a/examples/widgets/dialogs/standarddialogs/main.cpp +++ b/examples/widgets/dialogs/standarddialogs/main.cpp @@ -59,6 +59,7 @@ int main(int argc, char *argv[]) { + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QApplication app(argc, argv); QGuiApplication::setApplicationDisplayName(Dialog::tr("Standard Dialogs")); diff --git a/examples/widgets/dialogs/trivialwizard/trivialwizard.cpp b/examples/widgets/dialogs/trivialwizard/trivialwizard.cpp index fe49bf6304..ce13a59b0c 100644 --- a/examples/widgets/dialogs/trivialwizard/trivialwizard.cpp +++ b/examples/widgets/dialogs/trivialwizard/trivialwizard.cpp @@ -123,6 +123,8 @@ QWizardPage *createConclusionPage() int main(int argc, char *argv[]) //! [9] //! [11] { + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc, argv); #ifndef QT_NO_TRANSLATION -- cgit v1.2.3 From 7ab84cfe74f8d525f8099c2739f80681c3c6a428 Mon Sep 17 00:00:00 2001 From: Miguel Costa Date: Wed, 13 Jun 2018 17:04:22 +0200 Subject: factorial example: Fix issue with WinRT console output Replaced the display of the calculation output, generated using fprintf(stdout, ...), with qInfo() << ... In WinRT, fprintf to stdout does not cause output to be generated. Task-number: QTBUG-67566 Change-Id: I3b95bbf888e863683cbaf54deb26c3821433a5b8 Reviewed-by: Andre de la Rocha Reviewed-by: Maurice Kalinowski --- examples/widgets/statemachine/factorial/main.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'examples/widgets') diff --git a/examples/widgets/statemachine/factorial/main.cpp b/examples/widgets/statemachine/factorial/main.cpp index 2d25822828..e9431596fe 100644 --- a/examples/widgets/statemachine/factorial/main.cpp +++ b/examples/widgets/statemachine/factorial/main.cpp @@ -49,7 +49,6 @@ ****************************************************************************/ #include -#include //! [0] class Factorial : public QObject @@ -143,7 +142,7 @@ public: void onTransition(QEvent *) override { - fprintf(stdout, "%d\n", m_fact->property("fac").toInt()); + qInfo() << m_fact->property("fac").toInt(); } private: -- cgit v1.2.3