diff options
79 files changed, 2484 insertions, 1547 deletions
diff --git a/doc/global/externalsites/external-resources.qdoc b/doc/global/externalsites/external-resources.qdoc index 01c6939dca..1c3d37c199 100644 --- a/doc/global/externalsites/external-resources.qdoc +++ b/doc/global/externalsites/external-resources.qdoc @@ -72,6 +72,16 @@ */ /*! + \externalpage https://cmake.org/cmake/help/latest/manual/cmake-qt.7.html#autorcc + \title CMake AUTORCC Documentation +*/ + +/*! + \externalpage https://cmake.org/cmake/help/latest/manual/cmake-qt.7.html#autouic + \title CMake AUTOUIC Documentation +*/ + +/*! \externalpage https://cmake.org/cmake/help/latest/prop_tgt/LOCATION.html \title CMake LOCATION Documentation */ diff --git a/mkspecs/features/qml_module.prf b/mkspecs/features/qml_module.prf index dbf5b74355..57cfec78b3 100644 --- a/mkspecs/features/qml_module.prf +++ b/mkspecs/features/qml_module.prf @@ -50,10 +50,7 @@ builtin_resources { # Install rules qmldir.base = $$qmldir_path -# Tools need qmldir and plugins.qmltypes always installed on the file system - qmldir.files = $$qmldir_file -install_qml_files: qmldir.files += $$fq_qml_files qmldir.path = $$[QT_INSTALL_QML]/$$TARGETPATH INSTALLS += qmldir @@ -65,12 +62,12 @@ INSTALLS += qmlfiles !debug_and_release|!build_all|CONFIG(release, debug|release) { !prefix_build { - COPIES += qmldir + COPIES += qmldir qmlfiles } else { # For non-installed static builds, tools need qmldir and plugins.qmltypes # files in the build dir - qmldir2build.files = $$qmldir_file $$fq_aux_qml_files - qmldir2build.path = $$DESTDIR - COPIES += qmldir2build + qml2build.files = $$qmldir_file $$fq_aux_qml_files + qml2build.path = $$DESTDIR + COPIES += qml2build } } diff --git a/mkspecs/features/wasm/wasm.prf b/mkspecs/features/wasm/wasm.prf index de726c674c..54d351bfd5 100644 --- a/mkspecs/features/wasm/wasm.prf +++ b/mkspecs/features/wasm/wasm.prf @@ -67,7 +67,7 @@ contains(TEMPLATE, .*app) { # replacing the app name placeholder with the actual app name. apphtml.name = application main html file apphtml.output = $$DESTDIR/$$TARGET_HTML - apphtml.commands = sed -e s/APPNAME/$$TARGET_BASE/g $$WASM_PLUGIN_PATH/wasm_shell.html > $$DESTDIR/$$TARGET_HTML + apphtml.commands = sed -e s/@APPNAME@/$$TARGET_BASE/g $$WASM_PLUGIN_PATH/wasm_shell.html > $$DESTDIR/$$TARGET_HTML apphtml.input = $$WASM_PLUGIN_PATH/wasm_shell.html apphtml.depends = $$apphtml.input QMAKE_EXTRA_COMPILERS += apphtml diff --git a/qmake/doc/src/qmake-manual.qdoc b/qmake/doc/src/qmake-manual.qdoc index 48ca96ae92..b271abcee3 100644 --- a/qmake/doc/src/qmake-manual.qdoc +++ b/qmake/doc/src/qmake-manual.qdoc @@ -1154,8 +1154,9 @@ \target DEPENDPATH \section1 DEPENDPATH - Specifies a list of all directories to look in to resolve dependencies. This - variable is used when crawling through \c included files. + Specifies a list of directories for qmake to scan, to resolve dependencies. + This variable is used when qmake crawls through the header files that you + \c{#include} in your source code. \target DESTDIR \section1 DESTDIR diff --git a/qmake/generators/makefile.cpp b/qmake/generators/makefile.cpp index cfd71a911b..6a6cb24441 100644 --- a/qmake/generators/makefile.cpp +++ b/qmake/generators/makefile.cpp @@ -1995,14 +1995,11 @@ MakefileGenerator::writeExtraCompilerTargets(QTextStream &t) QString dep_cmd = replaceExtraCompilerVariables(tmp_dep_cmd, inpf, tmp_out, LocalShell); dep_cmd = dep_cd_cmd + fixEnvVariables(dep_cmd); if (FILE *proc = QT_POPEN(dep_cmd.toLatin1().constData(), QT_POPEN_READ)) { - QString indeps; - while(!feof(proc)) { - int read_in = (int)fread(buff, 1, 255, proc); - if(!read_in) - break; - indeps += QByteArray(buff, read_in); - } + QByteArray depData; + while (int read_in = feof(proc) ? 0 : (int)fread(buff, 1, 255, proc)) + depData.append(buff, read_in); QT_PCLOSE(proc); + const QString indeps = QString::fromLocal8Bit(depData); if(!indeps.isEmpty()) { QDir outDir(Option::output_dir); QStringList dep_cmd_deps = splitDeps(indeps, dep_lines); @@ -2083,14 +2080,11 @@ MakefileGenerator::writeExtraCompilerTargets(QTextStream &t) QString dep_cmd = replaceExtraCompilerVariables(tmp_dep_cmd, inpf, out, LocalShell); dep_cmd = dep_cd_cmd + fixEnvVariables(dep_cmd); if (FILE *proc = QT_POPEN(dep_cmd.toLatin1().constData(), QT_POPEN_READ)) { - QString indeps; - while(!feof(proc)) { - int read_in = (int)fread(buff, 1, 255, proc); - if(!read_in) - break; - indeps += QByteArray(buff, read_in); - } + QByteArray depData; + while (int read_in = feof(proc) ? 0 : (int)fread(buff, 1, 255, proc)) + depData.append(buff, read_in); QT_PCLOSE(proc); + const QString indeps = QString::fromLocal8Bit(depData); if(!indeps.isEmpty()) { QDir outDir(Option::output_dir); QStringList dep_cmd_deps = splitDeps(indeps, dep_lines); diff --git a/src/corelib/doc/snippets/cmake-macros/examples.cmake b/src/corelib/doc/snippets/cmake-macros/examples.cmake new file mode 100644 index 0000000000..bba082586f --- /dev/null +++ b/src/corelib/doc/snippets/cmake-macros/examples.cmake @@ -0,0 +1,26 @@ +#! [qt5_wrap_cpp] +set(SOURCES myapp.cpp main.cpp) +qt5_wrap_cpp(SOURCES myapp.h) +add_executable(myapp ${SOURCES}) +#! [qt5_wrap_cpp] + +#! [qt5_add_resources] +set(SOURCES main.cpp) +qt5_add_resources(SOURCES example.qrc) +add_executable(myapp ${SOURCES}) +#! [qt5_add_resources] + +#! [qt5_add_big_resources] +set(SOURCES main.cpp) +qt5_add_big_resources(SOURCES big_resource.qrc) +add_executable(myapp ${SOURCES}) +#! [qt5_add_big_resources] + +#! [qt5_add_binary_resources] +qt5_add_binary_resources(resources project.qrc OPTIONS -no-compress) +add_dependencies(myapp resources) +#! [qt5_add_binary_resources] + +#! [qt5_generate_moc] +qt5_generate_moc(main.cpp main.moc TARGET myapp) +#! [qt5_generate_moc] diff --git a/src/corelib/doc/src/cmake-macros.qdoc b/src/corelib/doc/src/cmake-macros.qdoc new file mode 100644 index 0000000000..6140e8be44 --- /dev/null +++ b/src/corelib/doc/src/cmake-macros.qdoc @@ -0,0 +1,212 @@ +/**************************************************************************** +** +** Copyright (C) 2019 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** 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. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: https://www.gnu.org/licenses/fdl-1.3.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! +\page qtcore-cmake-qt5-wrap-cpp.html +\ingroup cmake-macros-qtcore + +\title qt5_wrap_cpp + +\brief Creates \c{.moc} files from sources. + +\section1 Synopsis + +\badcode +qt5_wrap_cpp(<VAR> src_file1 [src_file2 ...] + [TARGET target] + [OPTIONS ...] + [DEPENDS ...]) +\endcode + +\section1 Description + +Creates rules for calling \l{moc}{Meta-Object Compiler (moc)} on the given +source files. For each input file, an output file is generated in the build +directory. The paths of the generated files are added to\c{<VAR>}. + +\note This is a low-level macro. See the \l{CMake AUTOMOC Documentation} for a +more convenient way to let source files be processed with \c{moc}. + +\section1 Options + +You can set an explicit \c{TARGET}. This will make sure that the target +properties \c{INCLUDE_DIRECTORIES} and \c{COMPILE_DEFINITIONS} are also used +when scanning the source files with \c{moc}. + +You can set additional \c{OPTIONS} that should be added to the \c{moc} calls. +You can find possible options in the \l{moc}{moc documentation}. + +\c{DEPENDS} allows you to add additional dependencies for recreation of the +generated files. This is useful when the sources have implicit dependencies, +like code for a Qt plugin that includes a \c{.json} file using the +Q_PLUGIN_METADATA() macro. + +\section1 Examples + +\snippet cmake-macros/examples.cmake qt5_wrap_cpp +*/ + +/*! +\page qtcore-cmake-qt5-add-resources.html +\ingroup cmake-macros-qtcore + +\title qt5_add_resources + +\brief Compiles binary resources into source code. + +\section1 Synopsis + +\badcode +qt5_add_resources(<VAR> file1.qrc [file2.qrc ...] + [OPTIONS ...]) +\endcode + +\section1 Description + +Creates source code from Qt resource files using the +\l{Resource Compiler (rcc)}. Paths to the generated source files are added to +\c{<VAR>}. + +\note This is a low-level macro. See the \l{CMake AUTORCC Documentation} for a +more convenient way to let Qt resource files be processed with \c{rcc}. +For embedding bigger resources, see \l qt5_add_big_resources. + +\section1 Arguments + +You can set additional \c{OPTIONS} that should be added to the \c{rcc} calls. +You can find possible options in the \l{rcc}{rcc documentation}. + +\section1 Examples + +\snippet cmake-macros/examples.cmake qt5_add_resources +*/ + +/*! +\page qtcore-cmake-qt5-add-big-resources.html +\ingroup cmake-macros-qtcore + +\title qt5_add_big_resources + +\brief Compiles big binary resources into object code. + +\section1 Synopsis + +\badcode +qt5_add_big_resources(<VAR> file1.qrc [file2.qrc ...] + [OPTIONS ...]) +\endcode + +\section1 Description + +Creates compiled object files from Qt resource files using the +\l{Resource Compiler (rcc)}. Paths to the generated files are added to +\c{<VAR>}. + +This is similar to \l qt5_add_resources, but directly generates object +files (\c .o, \c .obj) files instead of C++ source code. This allows to +embed bigger resources, where compiling to C++ sources and then to +binaries would be too time consuming or memory intensive. + +\section1 Arguments + +You can set additional \c{OPTIONS} that should be added to the \c{rcc} calls. +You can find possible options in the \l{rcc}{rcc documentation}. + +\section1 Examples + +\snippet cmake-macros/examples.cmake qt5_add_big_resources +*/ + +/*! +\page qtcore-cmake-qt5_add_binary_resources.html +\ingroup cmake-macros-qtcore + +\title qt5_add_binary_resources + +\brief Creates an \c{RCC} file from a list of Qt resource files. + +\section1 Synopsis + +\badcode +qt5_add_binary_resources(target file1.qrc [file2.qrc ...] + [DESTINATION ...] + [OPTIONS ...]) +\endcode + +\section1 Description + +Adds a custom \c target that compiles Qt resource files into a binary \c{.rcc} +file. + +\section1 Arguments + +\c{DESTINATION} sets the path of the generated \c{.rcc} file. The default is +\c{${CMAKE_CURRENT_BINARY_DIR}/${target}.rcc}. + +You can set additional \c{OPTIONS} that should be added to the \c{rcc} calls. +You can find possible options in the \l{rcc}{rcc documentation}. + +\section1 Examples + +\snippet cmake-macros/examples.cmake qt5_add_binary_resources +*/ + +/*! +\page qtcore-cmake-qt5-generate-moc.html +\ingroup cmake-macros-qtcore + +\title qt5_generate_moc + +\brief Calls moc on an input file. + +\section1 Synopsis + +\badcode +qt5_generate_moc(src_file dest_file + [TARGET target]) +\endcode + +\section1 Description + +Creates a rule to call the \l{moc}{Meta-Object Compiler (moc)} on \c src_file +and store the output in \c dest_file. + +\note This is a low-level macro. See the \l{CMake AUTOMOC Documentation} for a +more convenient way to let source files be processed with \c{moc}. +\l qt5_wrap_cpp is also similar, but automatically generates a temporary file +path for you. + +\section1 Arguments + +You can set an explicit \c{TARGET}. This will make sure that the target +properties \c{INCLUDE_DIRECTORIES} and \c{COMPILE_DEFINITIONS} are also used +when scanning the source files with \c{moc}. + +\section1 Examples + +\snippet cmake-macros/examples.cmake qt5_generate_moc +*/ diff --git a/src/corelib/io/qfilesystemengine_unix.cpp b/src/corelib/io/qfilesystemengine_unix.cpp index 5bab897d43..b78e037865 100644 --- a/src/corelib/io/qfilesystemengine_unix.cpp +++ b/src/corelib/io/qfilesystemengine_unix.cpp @@ -695,52 +695,36 @@ QFileSystemEntry QFileSystemEngine::canonicalName(const QFileSystemEntry &entry, Q_UNUSED(data); return QFileSystemEntry(slowCanonicalized(absoluteName(entry).filePath())); #else - char *ret = 0; -# if defined(Q_OS_DARWIN) - ret = (char*)malloc(PATH_MAX + 1); - if (ret && realpath(entry.nativeFilePath().constData(), (char*)ret) == 0) { - const int savedErrno = errno; // errno is checked below, and free() might change it - free(ret); - errno = savedErrno; - ret = 0; - } -# elif defined(Q_OS_ANDROID) - // On some Android versions, realpath() will return a path even if it does not exist - // To work around this, we check existence in advance. + char stack_result[PATH_MAX+1]; + char *resolved_name = nullptr; +# if defined(Q_OS_DARWIN) || defined(Q_OS_ANDROID) + // On some Android and macOS versions, realpath() will return a path even if + // it does not exist. To work around this, we check existence in advance. if (!data.hasFlags(QFileSystemMetaData::ExistsAttribute)) fillMetaData(entry, data, QFileSystemMetaData::ExistsAttribute); if (!data.exists()) { - ret = 0; errno = ENOENT; } else { - ret = (char*)malloc(PATH_MAX + 1); - if (realpath(entry.nativeFilePath().constData(), (char*)ret) == 0) { - const int savedErrno = errno; // errno is checked below, and free() might change it - free(ret); - errno = savedErrno; - ret = 0; - } + resolved_name = stack_result; } - + if (resolved_name && realpath(entry.nativeFilePath().constData(), resolved_name) == nullptr) + resolved_name = nullptr; # else -# if _POSIX_VERSION >= 200801L - ret = realpath(entry.nativeFilePath().constData(), (char*)0); +# if _POSIX_VERSION >= 200801L // ask realpath to allocate memory + resolved_name = realpath(entry.nativeFilePath().constData(), nullptr); # else - ret = (char*)malloc(PATH_MAX + 1); - if (realpath(entry.nativeFilePath().constData(), (char*)ret) == 0) { - const int savedErrno = errno; // errno is checked below, and free() might change it - free(ret); - errno = savedErrno; - ret = 0; - } + resolved_name = stack_result; + if (realpath(entry.nativeFilePath().constData(), resolved_name) == nullptr) + resolved_name = nullptr; # endif # endif - if (ret) { + if (resolved_name) { data.knownFlagsMask |= QFileSystemMetaData::ExistsAttribute; data.entryFlags |= QFileSystemMetaData::ExistsAttribute; - QString canonicalPath = QDir::cleanPath(QFile::decodeName(ret)); - free(ret); + QString canonicalPath = QDir::cleanPath(QFile::decodeName(resolved_name)); + if (resolved_name != stack_result) + free(resolved_name); return QFileSystemEntry(canonicalPath); } else if (errno == ENOENT || errno == ENOTDIR) { // file doesn't exist data.knownFlagsMask |= QFileSystemMetaData::ExistsAttribute; diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp index 625790abb8..b70c61e351 100644 --- a/src/corelib/kernel/qcoreapplication.cpp +++ b/src/corelib/kernel/qcoreapplication.cpp @@ -46,6 +46,7 @@ #include "qcoreevent.h" #include "qeventloop.h" #endif +#include "qmetaobject.h" #include "qcorecmdlineargs_p.h" #include <qdatastream.h> #include <qdebug.h> @@ -952,6 +953,10 @@ bool QCoreApplication::isSetuidAllowed() Sets the attribute \a attribute if \a on is true; otherwise clears the attribute. + \note Some application attributes must be set \b before creating a + QCoreApplication instance. Refer to the Qt::ApplicationAttribute + documentation for more information. + \sa testAttribute() */ void QCoreApplication::setAttribute(Qt::ApplicationAttribute attribute, bool on) @@ -960,6 +965,27 @@ void QCoreApplication::setAttribute(Qt::ApplicationAttribute attribute, bool on) QCoreApplicationPrivate::attribs |= 1 << attribute; else QCoreApplicationPrivate::attribs &= ~(1 << attribute); + if (Q_UNLIKELY(qApp)) { + switch (attribute) { + case Qt::AA_EnableHighDpiScaling: + case Qt::AA_DisableHighDpiScaling: + case Qt::AA_PluginApplication: + case Qt::AA_UseDesktopOpenGL: + case Qt::AA_UseOpenGLES: + case Qt::AA_UseSoftwareOpenGL: + case Qt::AA_ShareOpenGLContexts: +#ifdef QT_BOOTSTRAPPED + qWarning("Attribute %d must be set before QCoreApplication is created.", + attribute); +#else + qWarning("Attribute Qt::%s must be set before QCoreApplication is created.", + QMetaEnum::fromType<Qt::ApplicationAttribute>().valueToKey(attribute)); +#endif + break; + default: + break; + } + } } /*! diff --git a/src/corelib/kernel/qmetaobject.h b/src/corelib/kernel/qmetaobject.h index 10b14a7e03..fcd92afd89 100644 --- a/src/corelib/kernel/qmetaobject.h +++ b/src/corelib/kernel/qmetaobject.h @@ -230,7 +230,8 @@ public: template<typename T> static QMetaEnum fromType() { Q_STATIC_ASSERT_X(QtPrivate::IsQEnumHelper<T>::Value, - "QMetaEnum::fromType only works with enums declared as Q_ENUM or Q_FLAG"); + "QMetaEnum::fromType only works with enums declared as " + "Q_ENUM, Q_ENUM_NS, Q_FLAG or Q_FLAG_NS"); const QMetaObject *metaObject = qt_getEnumMetaObject(T()); const char *name = qt_getEnumName(T()); return metaObject->enumerator(metaObject->indexOfEnumerator(name)); diff --git a/src/corelib/plugin/qlibrary.cpp b/src/corelib/plugin/qlibrary.cpp index 0e32776c71..3aadd1a73b 100644 --- a/src/corelib/plugin/qlibrary.cpp +++ b/src/corelib/plugin/qlibrary.cpp @@ -74,7 +74,7 @@ QT_BEGIN_NAMESPACE # define QLIBRARY_AS_DEBUG true #endif -#if defined(Q_OS_UNIX) +#if defined(Q_OS_UNIX) || defined(Q_CC_MINGW) // We don't use separate debug and release libs on UNIX, so we want // to allow loading plugins, regardless of how they were built. # define QT_NO_DEBUG_PLUGIN_CHECK diff --git a/src/gui/doc/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp b/src/gui/doc/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp index 4266da0a11..a7e22e549d 100644 --- a/src/gui/doc/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp +++ b/src/gui/doc/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp @@ -50,8 +50,8 @@ //! [0] QStandardItemModel model(4, 4); -for (int row = 0; row < 4; ++row) { - for (int column = 0; column < 4; ++column) { +for (int row = 0; row < model.rowCount(); ++row) { + for (int column = 0; column < model.columnCount(); ++column) { QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column)); model.setItem(row, column, item); } diff --git a/src/gui/kernel/qhighdpiscaling.cpp b/src/gui/kernel/qhighdpiscaling.cpp index 4b85973e92..4f8e9a3817 100644 --- a/src/gui/kernel/qhighdpiscaling.cpp +++ b/src/gui/kernel/qhighdpiscaling.cpp @@ -492,5 +492,13 @@ QPoint QHighDpiScaling::origin(const QPlatformScreen *platformScreen) return platformScreen->geometry().topLeft(); } +QPoint QHighDpiScaling::origin(const QWindow *window) +{ + if (window && window->isTopLevel() && window->screen()) + return window->screen()->geometry().topLeft(); + + return QPoint(0, 0); +} + #endif //QT_NO_HIGHDPISCALING QT_END_NAMESPACE diff --git a/src/gui/kernel/qhighdpiscaling_p.h b/src/gui/kernel/qhighdpiscaling_p.h index 28cf7de75b..dfc6abf5ba 100644 --- a/src/gui/kernel/qhighdpiscaling_p.h +++ b/src/gui/kernel/qhighdpiscaling_p.h @@ -83,6 +83,7 @@ public: static qreal factor(const QPlatformScreen *platformScreen); static QPoint origin(const QScreen *screen); static QPoint origin(const QPlatformScreen *platformScreen); + static QPoint origin(const QWindow *window); static QPoint mapPositionToNative(const QPoint &pos, const QPlatformScreen *platformScreen); static QPoint mapPositionFromNative(const QPoint &pos, const QPlatformScreen *platformScreen); static QPoint mapPositionToGlobal(const QPoint &pos, const QPoint &windowGlobalPosition, const QWindow *window); @@ -203,94 +204,42 @@ inline QPointF toNativeLocalPosition(const QPointF &pos, const QWindow *window) return pos * scaleFactor; } -inline QRect fromNativePixels(const QRect &pixelRect, const QPlatformScreen *platformScreen) +template <typename C> +inline QRect fromNativePixels(const QRect &pixelRect, const C *context) { - const qreal scaleFactor = QHighDpiScaling::factor(platformScreen); - const QPoint origin = QHighDpiScaling::origin(platformScreen); + const qreal scaleFactor = QHighDpiScaling::factor(context); + const QPoint origin = QHighDpiScaling::origin(context); return QRect(fromNative(pixelRect.topLeft(), scaleFactor, origin), fromNative(pixelRect.size(), scaleFactor)); } -inline QRect toNativePixels(const QRect &pointRect, const QPlatformScreen *platformScreen) +template <typename C> +inline QRect toNativePixels(const QRect &pointRect, const C *context) { - const qreal scaleFactor = QHighDpiScaling::factor(platformScreen); - const QPoint origin = QHighDpiScaling::origin(platformScreen); + const qreal scaleFactor = QHighDpiScaling::factor(context); + const QPoint origin = QHighDpiScaling::origin(context); return QRect(toNative(pointRect.topLeft(), scaleFactor, origin), toNative(pointRect.size(), scaleFactor)); } -inline QRect fromNativePixels(const QRect &pixelRect, const QScreen *screen) +template <typename C> +inline QRectF toNativePixels(const QRectF &pointRect, const C *context) { - const qreal scaleFactor = QHighDpiScaling::factor(screen); - const QPoint origin = QHighDpiScaling::origin(screen); - return QRect(fromNative(pixelRect.topLeft(), scaleFactor, origin), - fromNative(pixelRect.size(), scaleFactor)); -} - -inline QRect toNativePixels(const QRect &pointRect, const QScreen *screen) -{ - const qreal scaleFactor = QHighDpiScaling::factor(screen); - const QPoint origin = QHighDpiScaling::origin(screen); - return QRect(toNative(pointRect.topLeft(), scaleFactor, origin), - toNative(pointRect.size(), scaleFactor)); -} - -inline QRect fromNativePixels(const QRect &pixelRect, const QWindow *window) -{ - if (window && window->isTopLevel() && window->screen()) { - return fromNativePixels(pixelRect, window->screen()); - } else { - const qreal scaleFactor = QHighDpiScaling::factor(window); - return QRect(pixelRect.topLeft() / scaleFactor, fromNative(pixelRect.size(), scaleFactor)); - } -} - -inline QRectF toNativePixels(const QRectF &pointRect, const QScreen *screen) -{ - const qreal scaleFactor = QHighDpiScaling::factor(screen); - const QPoint origin = QHighDpiScaling::origin(screen); + const qreal scaleFactor = QHighDpiScaling::factor(context); + const QPoint origin = QHighDpiScaling::origin(context); return QRectF(toNative(pointRect.topLeft(), scaleFactor, origin), - toNative(pointRect.size(), scaleFactor)); + toNative(pointRect.size(), scaleFactor)); } -inline QRect toNativePixels(const QRect &pointRect, const QWindow *window) +template <typename C> +inline QRectF fromNativePixels(const QRectF &pixelRect, const C *context) { - if (window && window->isTopLevel() && window->screen()) { - return toNativePixels(pointRect, window->screen()); - } else { - const qreal scaleFactor = QHighDpiScaling::factor(window); - return QRect(pointRect.topLeft() * scaleFactor, toNative(pointRect.size(), scaleFactor)); - } -} - -inline QRectF fromNativePixels(const QRectF &pixelRect, const QScreen *screen) -{ - const qreal scaleFactor = QHighDpiScaling::factor(screen); - const QPoint origin = QHighDpiScaling::origin(screen); + const qreal scaleFactor = QHighDpiScaling::factor(context); + const QPoint origin = QHighDpiScaling::origin(context); return QRectF(fromNative(pixelRect.topLeft(), scaleFactor, origin), fromNative(pixelRect.size(), scaleFactor)); } -inline QRectF fromNativePixels(const QRectF &pixelRect, const QWindow *window) -{ - if (window && window->isTopLevel() && window->screen()) { - return fromNativePixels(pixelRect, window->screen()); - } else { - const qreal scaleFactor = QHighDpiScaling::factor(window); - return QRectF(pixelRect.topLeft() / scaleFactor, pixelRect.size() / scaleFactor); - } -} - -inline QRectF toNativePixels(const QRectF &pointRect, const QWindow *window) -{ - if (window && window->isTopLevel() && window->screen()) { - return toNativePixels(pointRect, window->screen()); - } else { - const qreal scaleFactor = QHighDpiScaling::factor(window); - return QRectF(pointRect.topLeft() * scaleFactor, pointRect.size() * scaleFactor); - } -} - inline QSize fromNativePixels(const QSize &pixelSize, const QWindow *window) { return pixelSize / QHighDpiScaling::factor(window); @@ -311,56 +260,28 @@ inline QSizeF toNativePixels(const QSizeF &pointSize, const QWindow *window) return pointSize * QHighDpiScaling::factor(window); } -inline QPoint fromNativePixels(const QPoint &pixelPoint, const QScreen *screen) +template <typename C> +inline QPoint fromNativePixels(const QPoint &pixelPoint, const C *context) { - return fromNative(pixelPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen)); + return fromNative(pixelPoint, QHighDpiScaling::factor(context), QHighDpiScaling::origin(context)); } -inline QPoint fromNativePixels(const QPoint &pixelPoint, const QWindow *window) +template <typename C> +inline QPoint toNativePixels(const QPoint &pointPoint, const C *context) { - if (window && window->isTopLevel() && window->screen()) - return fromNativePixels(pixelPoint, window->screen()); - else - return pixelPoint / QHighDpiScaling::factor(window); + return toNative(pointPoint, QHighDpiScaling::factor(context), QHighDpiScaling::origin(context)); } -inline QPoint toNativePixels(const QPoint &pointPoint, const QScreen *screen) +template <typename C> +inline QPointF fromNativePixels(const QPointF &pixelPoint, const C *context) { - return toNative(pointPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen)); + return fromNative(pixelPoint, QHighDpiScaling::factor(context), QHighDpiScaling::origin(context)); } -inline QPoint toNativePixels(const QPoint &pointPoint, const QWindow *window) +template <typename C> +inline QPointF toNativePixels(const QPointF &pointPoint, const C *context) { - if (window && window->isTopLevel() && window->screen()) - return toNativePixels(pointPoint, window->screen()); - else - return pointPoint * QHighDpiScaling::factor(window); -} - -inline QPointF fromNativePixels(const QPointF &pixelPoint, const QScreen *screen) -{ - return fromNative(pixelPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen)); -} - -inline QPointF fromNativePixels(const QPointF &pixelPoint, const QWindow *window) -{ - if (window && window->isTopLevel() && window->screen()) - return fromNativePixels(pixelPoint, window->screen()); - else - return pixelPoint / QHighDpiScaling::factor(window); -} - -inline QPointF toNativePixels(const QPointF &pointPoint, const QScreen *screen) -{ - return toNative(pointPoint, QHighDpiScaling::factor(screen), QHighDpiScaling::origin(screen)); -} - -inline QPointF toNativePixels(const QPointF &pointPoint, const QWindow *window) -{ - if (window && window->isTopLevel() && window->screen()) - return toNativePixels(pointPoint, window->screen()); - else - return pointPoint * QHighDpiScaling::factor(window); + return toNative(pointPoint, QHighDpiScaling::factor(context), QHighDpiScaling::origin(context)); } inline QMargins fromNativePixels(const QMargins &pixelMargins, const QWindow *window) @@ -425,47 +346,26 @@ inline QRegion toNativeLocalRegion(const QRegion &pointRegion, const QWindow *wi } // Any T that has operator/() -template <typename T> -T fromNativePixels(const T &pixelValue, const QWindow *window) -{ - if (!QHighDpiScaling::isActive()) - return pixelValue; - - return pixelValue / QHighDpiScaling::factor(window); - -} - - //##### ????? -template <typename T> -T fromNativePixels(const T &pixelValue, const QScreen *screen) +template <typename T, typename C> +T fromNativePixels(const T &pixelValue, const C *context) { if (!QHighDpiScaling::isActive()) return pixelValue; - return pixelValue / QHighDpiScaling::factor(screen); + return pixelValue / QHighDpiScaling::factor(context); } // Any T that has operator*() -template <typename T> -T toNativePixels(const T &pointValue, const QWindow *window) -{ - if (!QHighDpiScaling::isActive()) - return pointValue; - - return pointValue * QHighDpiScaling::factor(window); -} - -template <typename T> -T toNativePixels(const T &pointValue, const QScreen *screen) +template <typename T, typename C> +T toNativePixels(const T &pointValue, const C *context) { if (!QHighDpiScaling::isActive()) return pointValue; - return pointValue * QHighDpiScaling::factor(screen); + return pointValue * QHighDpiScaling::factor(context); } - // Any QVector<T> where T has operator/() template <typename T> QVector<T> fromNativePixels(const QVector<T> &pixelValues, const QWindow *window) diff --git a/src/gui/kernel/qplatformtheme.cpp b/src/gui/kernel/qplatformtheme.cpp index 277d976dde..f906f808d8 100644 --- a/src/gui/kernel/qplatformtheme.cpp +++ b/src/gui/kernel/qplatformtheme.cpp @@ -471,6 +471,8 @@ QVariant QPlatformTheme::themeHint(ThemeHint hint) const return QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::ItemViewActivateItemOnSingleClick); case QPlatformTheme::UiEffects: return QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::UiEffects); + case QPlatformTheme::ShowShortcutsInContextMenus: + return QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::ShowShortcutsInContextMenus); default: return QPlatformTheme::defaultThemeHint(hint); } @@ -521,7 +523,7 @@ QVariant QPlatformTheme::defaultThemeHint(ThemeHint hint) case QPlatformTheme::StyleNames: return QVariant(QStringList()); case QPlatformTheme::ShowShortcutsInContextMenus: - return QVariant(false); + return QVariant(true); case TextCursorWidth: return QVariant(1); case DropShadow: diff --git a/src/gui/kernel/qplatformwindow.cpp b/src/gui/kernel/qplatformwindow.cpp index 562289a8c9..4e95751397 100644 --- a/src/gui/kernel/qplatformwindow.cpp +++ b/src/gui/kernel/qplatformwindow.cpp @@ -705,14 +705,20 @@ QRect QPlatformWindow::initialGeometry(const QWindow *w, w, defaultWidth, defaultHeight); return QRect(initialGeometry.topLeft(), QHighDpi::toNative(size, factor)); } - const QScreen *screen = effectiveScreen(w); + const auto *wp = qt_window_private(const_cast<QWindow*>(w)); + const bool position = wp->positionAutomatic && w->type() != Qt::Popup; + if (!position && !wp->resizeAutomatic) + return initialGeometry; + const QScreen *screen = wp->positionAutomatic + ? effectiveScreen(w) + : QGuiApplication::screenAt(initialGeometry.center()); if (!screen) return initialGeometry; - const auto *wp = qt_window_private(const_cast<QWindow*>(w)); + // initialGeometry refers to window's screen QRect rect(QHighDpi::fromNativePixels(initialGeometry, w)); if (wp->resizeAutomatic) rect.setSize(fixInitialSize(rect.size(), w, defaultWidth, defaultHeight)); - if (wp->positionAutomatic && w->type() != Qt::Popup) { + if (position) { const QRect availableGeometry = screen->availableGeometry(); // Center unless the geometry ( + unknown window frame) is too large for the screen). if (rect.height() < (availableGeometry.height() * 8) / 9 diff --git a/src/gui/painting/qpaintengine_raster_p.h b/src/gui/painting/qpaintengine_raster_p.h index 500e0fae54..ec4a35087a 100644 --- a/src/gui/painting/qpaintengine_raster_p.h +++ b/src/gui/painting/qpaintengine_raster_p.h @@ -434,7 +434,7 @@ public: QImage::Format prepare(QImage *image); - uchar *scanLine(int y) { Q_ASSERT(y>=0); Q_ASSERT(y<m_height); return m_buffer + y * bytes_per_line; } + uchar *scanLine(int y) { Q_ASSERT(y>=0); Q_ASSERT(y<m_height); return m_buffer + y * qsizetype(bytes_per_line); } int width() const { return m_width; } int height() const { return m_height; } diff --git a/src/gui/text/qtextodfwriter.cpp b/src/gui/text/qtextodfwriter.cpp index 4c89492795..3561c185a6 100644 --- a/src/gui/text/qtextodfwriter.cpp +++ b/src/gui/text/qtextodfwriter.cpp @@ -43,6 +43,7 @@ #include "qtextodfwriter_p.h" +#include <QImageReader> #include <QImageWriter> #include <QTextListFormat> #include <QTextList> @@ -410,6 +411,29 @@ void QTextOdfWriter::writeBlock(QXmlStreamWriter &writer, const QTextBlock &bloc writer.writeEndElement(); // list-item } +static bool probeImageData(QIODevice *device, QImage *image, QString *mimeType, qreal *width, qreal *height) +{ + QImageReader reader(device); + const QByteArray format = reader.format().toLower(); + if (format == "png") { + *mimeType = QStringLiteral("image/png"); + } else if (format == "jpg") { + *mimeType = QStringLiteral("image/jpg"); + } else if (format == "svg") { + *mimeType = QStringLiteral("image/svg+xml"); + } else { + *image = reader.read(); + return false; + } + + const QSize size = reader.size(); + + *width = size.width(); + *height = size.height(); + + return true; +} + void QTextOdfWriter::writeInlineCharacter(QXmlStreamWriter &writer, const QTextFragment &fragment) const { writer.writeStartElement(drawNS, QString::fromLatin1("frame")); @@ -420,47 +444,73 @@ void QTextOdfWriter::writeInlineCharacter(QXmlStreamWriter &writer, const QTextF QTextImageFormat imageFormat = fragment.charFormat().toImageFormat(); writer.writeAttribute(drawNS, QString::fromLatin1("name"), imageFormat.name()); + QByteArray data; + QString mimeType; + qreal width = 0; + qreal height = 0; + QImage image; QString name = imageFormat.name(); if (name.startsWith(QLatin1String(":/"))) // auto-detect resources name.prepend(QLatin1String("qrc")); QUrl url = QUrl(name); - const QVariant data = m_document->resource(QTextDocument::ImageResource, url); - if (data.type() == QVariant::Image) { - image = qvariant_cast<QImage>(data); - } else if (data.type() == QVariant::ByteArray) { - image.loadFromData(data.toByteArray()); - } - - if (image.isNull()) { - if (image.isNull()) { // try direct loading - name = imageFormat.name(); // remove qrc:/ prefix again - image.load(name); + const QVariant variant = m_document->resource(QTextDocument::ImageResource, url); + if (variant.type() == QVariant::Image) { + image = qvariant_cast<QImage>(variant); + } else if (variant.type() == QVariant::ByteArray) { + data = variant.toByteArray(); + + QBuffer buffer(&data); + buffer.open(QIODevice::ReadOnly); + probeImageData(&buffer, &image, &mimeType, &width, &height); + } else { + // try direct loading + QFile file(imageFormat.name()); + if (file.open(QIODevice::ReadOnly) && !probeImageData(&file, &image, &mimeType, &width, &height)) { + file.seek(0); + data = file.readAll(); } } if (! image.isNull()) { QBuffer imageBytes; - QString filename = m_strategy->createUniqueImageName(); + int imgQuality = imageFormat.quality(); if (imgQuality >= 100 || imgQuality < 0 || image.hasAlphaChannel()) { QImageWriter imageWriter(&imageBytes, "png"); imageWriter.write(image); - m_strategy->addFile(filename, QString::fromLatin1("image/png"), imageBytes.data()); + + data = imageBytes.data(); + mimeType = QStringLiteral("image/png"); } else { // Write images without alpha channel as jpg with quality set by QTextImageFormat QImageWriter imageWriter(&imageBytes, "jpg"); imageWriter.setQuality(imgQuality); imageWriter.write(image); - m_strategy->addFile(filename, QString::fromLatin1("image/jpg"), imageBytes.data()); + + data = imageBytes.data(); + mimeType = QStringLiteral("image/jpg"); } - // get the width/height from the format. - qreal width = imageFormat.hasProperty(QTextFormat::ImageWidth) - ? imageFormat.width() : image.width(); + + width = image.width(); + height = image.height(); + } + + if (!data.isEmpty()) { + if (imageFormat.hasProperty(QTextFormat::ImageWidth)) { + width = imageFormat.width(); + } + if (imageFormat.hasProperty(QTextFormat::ImageHeight)) { + height = imageFormat.height(); + } + + QString filename = m_strategy->createUniqueImageName(); + + m_strategy->addFile(filename, mimeType, data); + writer.writeAttribute(svgNS, QString::fromLatin1("width"), pixelToPoint(width)); - qreal height = imageFormat.hasProperty(QTextFormat::ImageHeight) - ? imageFormat.height() : image.height(); writer.writeAttribute(svgNS, QString::fromLatin1("height"), pixelToPoint(height)); + writer.writeAttribute(textNS, QStringLiteral("anchor-type"), QStringLiteral("as-char")); writer.writeStartElement(drawNS, QString::fromLatin1("image")); writer.writeAttribute(xlinkNS, QString::fromLatin1("href"), filename); writer.writeEndElement(); // image diff --git a/src/network/access/qnetworkreplywasmimpl.cpp b/src/network/access/qnetworkreplywasmimpl.cpp index bb6ef07741..9f8a42ad89 100644 --- a/src/network/access/qnetworkreplywasmimpl.cpp +++ b/src/network/access/qnetworkreplywasmimpl.cpp @@ -235,7 +235,7 @@ void QNetworkReplyWasmImpl::close() void QNetworkReplyWasmImpl::abort() { Q_D(const QNetworkReplyWasmImpl); - setError( QNetworkReply::OperationCanceledError, "Operation canceled" ); + setError( QNetworkReply::OperationCanceledError, QStringLiteral("Operation canceled")); d->doAbort(); close(); @@ -328,8 +328,6 @@ void QNetworkReplyWasmImplPrivate::doSendRequest() m_xhr = val::global("XMLHttpRequest").new_(); std::string verb = q->methodName().toStdString(); - QString extraDataString; - m_xhr.call<void>("open", verb, request.url().toString().toStdString()); m_xhr.set("onerror", val::module_property("qt_QNetworkReplyWasmImplPrivate_requestErrorCallback")); @@ -348,30 +346,12 @@ void QNetworkReplyWasmImplPrivate::doSendRequest() if (outgoingData) // data from post request extraData = outgoingData->readAll(); - if (contentType.contains("text") || - contentType.contains("json") || - contentType.contains("form")) { - if (extraData.size() > 0) - extraDataString.fromUtf8(extraData); - } - if (contentType.contains("json")) { - if (!extraDataString.isEmpty()) { - m_xhr.set("responseType", val("json")); - dataToSend = val(extraDataString.toStdString()); - } - } else if (contentType.contains("form")) { //construct form data - if (!extraDataString.isEmpty()) { - val formData = val::global("FormData").new_(); - QStringList formList = extraDataString.split('&'); - - for (auto formEntry : formList) { - formData.call<void>("append", formEntry.split('=')[0].toStdString(), formEntry.split('=')[1].toStdString()); - } - dataToSend = formData; - } - } else { - m_xhr.set("responseType", val("blob")); + if (!extraData.isEmpty()) { + dataToSend = val(typed_memory_view(extraData.size(), + reinterpret_cast<const unsigned char *> + (extraData.constData()))); } + m_xhr.set("responseType", val("blob")); // set request headers for (auto header : request.rawHeaderList()) { m_xhr.call<void>("setRequestHeader", header.toStdString(), request.rawHeader(header).toStdString()); diff --git a/src/openglextensions/qopenglextensions.h b/src/openglextensions/qopenglextensions.h index 59dbdd4f12..439e0e6530 100644 --- a/src/openglextensions/qopenglextensions.h +++ b/src/openglextensions/qopenglextensions.h @@ -66,10 +66,10 @@ #include <QtGui/qopengl.h> -class QOpenGLContext; - QT_BEGIN_NAMESPACE +class QOpenGLContext; + #if 0 // silence syncqt warnings #pragma qt_class(QOpenGLExtensions) diff --git a/src/platformsupport/clipboard/qmacmime.mm b/src/platformsupport/clipboard/qmacmime.mm index f425e34b39..76e9c8712c 100644 --- a/src/platformsupport/clipboard/qmacmime.mm +++ b/src/platformsupport/clipboard/qmacmime.mm @@ -435,8 +435,23 @@ QList<QByteArray> QMacPasteboardMimeUnicodeText::convertFromMime(const QString & if (flavor == QLatin1String("public.utf8-plain-text")) ret.append(string.toUtf8()); #if QT_CONFIG(textcodec) - else if (flavor == QLatin1String("public.utf16-plain-text")) - ret.append(QTextCodec::codecForName("UTF-16")->fromUnicode(string)); + else if (flavor == QLatin1String("public.utf16-plain-text")) { + QTextCodec::ConverterState state; +#if defined(Q_OS_MACOS) + // Some applications such as Microsoft Excel, don't deal well with + // a BOM present, so we follow the traditional approach of Qt on + // macOS to not generate public.utf16-plain-text with a BOM. + state.flags = QTextCodec::IgnoreHeader; +#else + // Whereas iOS applications will fail to paste if we do _not_ + // include a BOM in the public.utf16-plain-text content, most + // likely due to converting the data using NSUTF16StringEncoding + // which assumes big-endian byte order if there is no BOM. + state.flags = QTextCodec::DefaultConversion; +#endif + ret.append(QTextCodec::codecForName("UTF-16")->fromUnicode( + string.constData(), string.length(), &state)); + } #endif return ret; } diff --git a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp index 40db7dbac7..99666bcec6 100644 --- a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp +++ b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp @@ -984,7 +984,7 @@ QFontEngineFT::Glyph *QFontEngineFT::loadGlyph(QGlyphSet *set, uint glyph, || matrix.xy != 0 || matrix.yx != 0; - if (transform || (format != Format_Mono && !isScalableBitmap())) + if (transform || obliquen || (format != Format_Mono && !isScalableBitmap())) load_flags |= FT_LOAD_NO_BITMAP; FT_Error err = FT_Load_Glyph(face, glyph, load_flags); diff --git a/src/platformsupport/kmsconvenience/qkmsdevice.cpp b/src/platformsupport/kmsconvenience/qkmsdevice.cpp index 5838c43eca..8cc7a539b5 100644 --- a/src/platformsupport/kmsconvenience/qkmsdevice.cpp +++ b/src/platformsupport/kmsconvenience/qkmsdevice.cpp @@ -581,10 +581,16 @@ void QKmsDevice::createScreens() #if QT_CONFIG(drm_atomic) // check atomic support - m_has_atomic_support = !drmSetClientCap(m_dri_fd, DRM_CLIENT_CAP_ATOMIC, 1) - && qEnvironmentVariableIntValue("QT_QPA_EGLFS_KMS_ATOMIC"); - if (m_has_atomic_support) - qCDebug(qLcKmsDebug) << "Atomic Support found"; + m_has_atomic_support = !drmSetClientCap(m_dri_fd, DRM_CLIENT_CAP_ATOMIC, 1); + if (m_has_atomic_support) { + qCDebug(qLcKmsDebug, "Atomic reported as supported"); + if (qEnvironmentVariableIntValue("QT_QPA_EGLFS_KMS_ATOMIC")) { + qCDebug(qLcKmsDebug, "Atomic enabled"); + } else { + qCDebug(qLcKmsDebug, "Atomic disabled"); + m_has_atomic_support = false; + } + } #endif drmModeResPtr resources = drmModeGetResources(m_dri_fd); diff --git a/src/platformsupport/linuxaccessibility/dbusconnection.cpp b/src/platformsupport/linuxaccessibility/dbusconnection.cpp index 3e2248a018..cacbfdae9f 100644 --- a/src/platformsupport/linuxaccessibility/dbusconnection.cpp +++ b/src/platformsupport/linuxaccessibility/dbusconnection.cpp @@ -71,6 +71,10 @@ DBusConnection::DBusConnection(QObject *parent) { // Start monitoring if "org.a11y.Bus" is registered as DBus service. QDBusConnection c = QDBusConnection::sessionBus(); + if (!c.isConnected()) { + return; + } + dbusWatcher = new QDBusServiceWatcher(A11Y_SERVICE, c, QDBusServiceWatcher::WatchForRegistration, this); connect(dbusWatcher, SIGNAL(serviceRegistered(QString)), this, SLOT(serviceRegistered())); diff --git a/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h b/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h index 64c54c694a..fd39b6ee33 100644 --- a/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h +++ b/src/platformsupport/windowsuiautomation/uiaserverinterfaces_p.h @@ -360,4 +360,27 @@ __CRT_UUID_DECL(IGridItemProvider, 0xd02541f1, 0xfb81, 0x4d64, 0xae,0x32, 0xf5,0 #endif #endif + +#ifndef __IWindowProvider_INTERFACE_DEFINED__ +#define __IWindowProvider_INTERFACE_DEFINED__ +DEFINE_GUID(IID_IWindowProvider, 0x987df77b, 0xdb06, 0x4d77, 0x8f,0x8a, 0x86,0xa9,0xc3,0xbb,0x90,0xb9); +MIDL_INTERFACE("987df77b-db06-4d77-8f8a-86a9c3bb90b9") +IWindowProvider : public IUnknown +{ +public: + virtual HRESULT STDMETHODCALLTYPE SetVisualState(enum WindowVisualState state) = 0; + virtual HRESULT STDMETHODCALLTYPE Close( void) = 0; + virtual HRESULT STDMETHODCALLTYPE WaitForInputIdle(int milliseconds, __RPC__out BOOL *pRetVal) = 0; + virtual HRESULT STDMETHODCALLTYPE get_CanMaximize(__RPC__out BOOL *pRetVal) = 0; + virtual HRESULT STDMETHODCALLTYPE get_CanMinimize(__RPC__out BOOL *pRetVal) = 0; + virtual HRESULT STDMETHODCALLTYPE get_IsModal(__RPC__out BOOL *pRetVal) = 0; + virtual HRESULT STDMETHODCALLTYPE get_WindowVisualState(__RPC__out enum WindowVisualState *pRetVal) = 0; + virtual HRESULT STDMETHODCALLTYPE get_WindowInteractionState(__RPC__out enum WindowInteractionState *pRetVal) = 0; + virtual HRESULT STDMETHODCALLTYPE get_IsTopmost(__RPC__out BOOL *pRetVal) = 0; +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IWindowProvider, 0x987df77b, 0xdb06, 0x4d77, 0x8f,0x8a, 0x86,0xa9,0xc3,0xbb,0x90,0xb9) +#endif +#endif + #endif diff --git a/src/platformsupport/windowsuiautomation/uiatypes_p.h b/src/platformsupport/windowsuiautomation/uiatypes_p.h index ea58417943..8ef71843a3 100644 --- a/src/platformsupport/windowsuiautomation/uiatypes_p.h +++ b/src/platformsupport/windowsuiautomation/uiatypes_p.h @@ -141,6 +141,20 @@ enum PropertyConditionFlags { PropertyConditionFlags_IgnoreCase = 1 }; +enum WindowVisualState { + WindowVisualState_Normal = 0, + WindowVisualState_Maximized = 1, + WindowVisualState_Minimized = 2 +}; + +enum WindowInteractionState { + WindowInteractionState_Running = 0, + WindowInteractionState_Closing = 1, + WindowInteractionState_ReadyForUserInteraction = 2, + WindowInteractionState_BlockedByModalWindow = 3, + WindowInteractionState_NotResponding = 4 +}; + struct UiaRect { double left; double top; diff --git a/src/plugins/platforms/android/qandroidinputcontext.cpp b/src/plugins/platforms/android/qandroidinputcontext.cpp index 07a6b52dbe..db40c30d7d 100644 --- a/src/plugins/platforms/android/qandroidinputcontext.cpp +++ b/src/plugins/platforms/android/qandroidinputcontext.cpp @@ -1129,46 +1129,63 @@ QString QAndroidInputContext::getSelectedText(jint /*flags*/) QString QAndroidInputContext::getTextAfterCursor(jint length, jint /*flags*/) { - //### the preedit text could theoretically be after the cursor - QVariant textAfter = QInputMethod::queryFocusObject(Qt::ImTextAfterCursor, QVariant(length)); - if (textAfter.isValid()) { - return textAfter.toString().left(length); - } - - //compatibility code for old controls that do not implement the new API - QSharedPointer<QInputMethodQueryEvent> query = focusObjectInputMethodQuery(); - if (query.isNull()) + if (length <= 0) return QString(); - QString text = query->value(Qt::ImSurroundingText).toString(); - if (!text.length()) - return text; + QString text; - int cursorPos = query->value(Qt::ImCursorPosition).toInt(); - return text.mid(cursorPos, length); + QVariant reportedTextAfter = QInputMethod::queryFocusObject(Qt::ImTextAfterCursor, length); + if (reportedTextAfter.isValid()) { + text = reportedTextAfter.toString(); + } else { + // Compatibility code for old controls that do not implement the new API + QSharedPointer<QInputMethodQueryEvent> query = + focusObjectInputMethodQuery(Qt::ImCursorPosition | Qt::ImSurroundingText); + if (query) { + const int cursorPos = query->value(Qt::ImCursorPosition).toInt(); + text = query->value(Qt::ImSurroundingText).toString().mid(cursorPos); + } + } + + // Controls do not report preedit text, so we have to add it + if (!m_composingText.isEmpty()) { + const int cursorPosInsidePreedit = m_composingCursor - m_composingTextStart; + text = m_composingText.midRef(cursorPosInsidePreedit) + text; + } + + text.truncate(length); + return text; } QString QAndroidInputContext::getTextBeforeCursor(jint length, jint /*flags*/) { - QVariant textBefore = QInputMethod::queryFocusObject(Qt::ImTextBeforeCursor, QVariant(length)); - if (textBefore.isValid()) - return textBefore.toString().rightRef(length) + m_composingText; - - //compatibility code for old controls that do not implement the new API - QSharedPointer<QInputMethodQueryEvent> query = focusObjectInputMethodQuery(); - if (query.isNull()) + if (length <= 0) return QString(); - int cursorPos = query->value(Qt::ImCursorPosition).toInt(); - QString text = query->value(Qt::ImSurroundingText).toString(); - if (!text.length()) - return text; + QString text; - //### the preedit text does not need to be immediately before the cursor - if (cursorPos <= length) - return text.leftRef(cursorPos) + m_composingText; - else - return text.midRef(cursorPos - length, length) + m_composingText; + QVariant reportedTextBefore = QInputMethod::queryFocusObject(Qt::ImTextBeforeCursor, length); + if (reportedTextBefore.isValid()) { + text = reportedTextBefore.toString(); + } else { + // Compatibility code for old controls that do not implement the new API + QSharedPointer<QInputMethodQueryEvent> query = + focusObjectInputMethodQuery(Qt::ImCursorPosition | Qt::ImSurroundingText); + if (query) { + const int cursorPos = query->value(Qt::ImCursorPosition).toInt(); + text = query->value(Qt::ImSurroundingText).toString().left(cursorPos); + } + } + + // Controls do not report preedit text, so we have to add it + if (!m_composingText.isEmpty()) { + const int cursorPosInsidePreedit = m_composingCursor - m_composingTextStart; + text += m_composingText.leftRef(cursorPosInsidePreedit); + } + + if (text.length() > length) + text = text.right(length); + return text; } /* @@ -1231,6 +1248,8 @@ jboolean QAndroidInputContext::setComposingRegion(jint start, jint end) if (query.isNull()) return JNI_FALSE; + if (start == end) + return JNI_TRUE; if (start > end) qSwap(start, end); diff --git a/src/plugins/platforms/cocoa/qcocoaintegration.mm b/src/plugins/platforms/cocoa/qcocoaintegration.mm index 1d35d9f440..300082d694 100644 --- a/src/plugins/platforms/cocoa/qcocoaintegration.mm +++ b/src/plugins/platforms/cocoa/qcocoaintegration.mm @@ -403,8 +403,13 @@ QCocoaServices *QCocoaIntegration::services() const QVariant QCocoaIntegration::styleHint(StyleHint hint) const { - if (hint == QPlatformIntegration::FontSmoothingGamma) + switch (hint) { + case FontSmoothingGamma: return QCoreTextFontEngine::fontSmoothingGamma(); + case ShowShortcutsInContextMenus: + return QVariant(false); + default: break; + } return QPlatformIntegration::styleHint(hint); } diff --git a/src/plugins/platforms/cocoa/qmacclipboard.mm b/src/plugins/platforms/cocoa/qmacclipboard.mm index ba6cfca219..358a6b49fd 100644 --- a/src/plugins/platforms/cocoa/qmacclipboard.mm +++ b/src/plugins/platforms/cocoa/qmacclipboard.mm @@ -489,19 +489,16 @@ QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const QMacInternalPasteboardMime *c = mimes.at(mime); QString c_flavor = c->flavorFor(format); if (!c_flavor.isEmpty()) { - // Handle text/plain a little differently. Try handling Unicode first. - bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text") - || c_flavor == QLatin1String("public.utf8-plain-text")); - if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) { - // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped - // correctly (as '\n') in this data. The 'public.utf16-plain-text' type - // usually maps newlines to '\r' instead. + // Converting via PasteboardCopyItemFlavorData below will for some UITs result + // in newlines mapping to '\r' instead of '\n'. To work around this we shortcut + // the conversion via NSPasteboard's NSStringPboardType if possible. + if (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text") + || c_flavor == QLatin1String("public.utf8-plain-text") + || c_flavor == QLatin1String("public.utf16-plain-text")) { QString str = qt_mac_get_pasteboardString(paste); if (!str.isEmpty()) return str; } - if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text"))) - c_flavor = QLatin1String("public.utf16-plain-text"); QVariant ret; QList<QByteArray> retList; diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_openwfd/qeglfsopenwfdintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_openwfd/qeglfsopenwfdintegration.cpp index 738c30c65a..b8f04cf978 100644 --- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_openwfd/qeglfsopenwfdintegration.cpp +++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_openwfd/qeglfsopenwfdintegration.cpp @@ -221,7 +221,7 @@ EGLNativeWindowType QEglFSOpenWFDIntegration::createNativeWindow(QPlatformWindow QSurfaceFormat QEglFSOpenWFDIntegration::surfaceFormatFor(const QSurfaceFormat &inputFormat) const { - QSurfaceFormat format; + QSurfaceFormat format = inputFormat; format.setRedBufferSize(8); format.setGreenBufferSize(8); format.setBlueBufferSize(8); diff --git a/src/plugins/platforms/ios/qiostextinputoverlay.mm b/src/plugins/platforms/ios/qiostextinputoverlay.mm index e5419b1766..0561a826c6 100644 --- a/src/plugins/platforms/ios/qiostextinputoverlay.mm +++ b/src/plugins/platforms/ios/qiostextinputoverlay.mm @@ -834,9 +834,14 @@ static void executeBlockWithoutAnimation(Block block) - (void)updateSelection { if (!hasSelection()) { - _cursorLayer.visible = NO; - _anchorLayer.visible = NO; - QIOSTextInputOverlay::s_editMenu.visible = NO; + if (_cursorLayer.visible) { + _cursorLayer.visible = NO; + _anchorLayer.visible = NO; + // Only hide the edit menu if we had a selection from before, since + // the edit menu can also be used for other purposes by others (in + // which case we try our best not to interfere). + QIOSTextInputOverlay::s_editMenu.visible = NO; + } return; } diff --git a/src/plugins/platforms/wasm/qwasmintegration.cpp b/src/plugins/platforms/wasm/qwasmintegration.cpp index 150783e193..31b9104de1 100644 --- a/src/plugins/platforms/wasm/qwasmintegration.cpp +++ b/src/plugins/platforms/wasm/qwasmintegration.cpp @@ -48,6 +48,7 @@ #include <QtGui/qscreen.h> #include <qpa/qwindowsysteminterface.h> #include <QtCore/qcoreapplication.h> +#include <qpa/qplatforminputcontextfactory_p.h> #include <emscripten/bind.h> #include <emscripten/val.h> @@ -180,6 +181,18 @@ QPlatformOpenGLContext *QWasmIntegration::createPlatformOpenGLContext(QOpenGLCon } #endif +void QWasmIntegration::initialize() +{ + QString icStr = QPlatformInputContextFactory::requested(); + if (!icStr.isNull()) + m_inputContext.reset(QPlatformInputContextFactory::create(icStr)); +} + +QPlatformInputContext *QWasmIntegration::inputContext() const +{ + return m_inputContext.data(); +} + QPlatformFontDatabase *QWasmIntegration::fontDatabase() const { if (m_fontDb == nullptr) diff --git a/src/plugins/platforms/wasm/qwasmintegration.h b/src/plugins/platforms/wasm/qwasmintegration.h index 6bd2f857db..c04c0eaecc 100644 --- a/src/plugins/platforms/wasm/qwasmintegration.h +++ b/src/plugins/platforms/wasm/qwasmintegration.h @@ -34,6 +34,7 @@ #include <qpa/qplatformintegration.h> #include <qpa/qplatformscreen.h> +#include <qpa/qplatforminputcontext.h> #include <QtCore/qhash.h> @@ -73,6 +74,9 @@ public: QPlatformTheme *createPlatformTheme(const QString &name) const override; QPlatformServices *services() const override; QPlatformClipboard *clipboard() const override; + void initialize() override; + QPlatformInputContext *inputContext() const override; + QWasmClipboard *getWasmClipboard() { return m_clipboard; } static QWasmIntegration *get() { return s_instance; } @@ -91,6 +95,7 @@ private: QHash<QString, QWasmScreen *> m_screens; mutable QWasmClipboard *m_clipboard; qreal m_fontDpi = -1; + mutable QScopedPointer<QPlatformInputContext> m_inputContext; static QWasmIntegration *s_instance; }; diff --git a/src/plugins/platforms/wasm/qwasmopenglcontext.cpp b/src/plugins/platforms/wasm/qwasmopenglcontext.cpp index ae43e2ebf0..1658f32f9e 100644 --- a/src/plugins/platforms/wasm/qwasmopenglcontext.cpp +++ b/src/plugins/platforms/wasm/qwasmopenglcontext.cpp @@ -37,6 +37,14 @@ QWasmOpenGLContext::QWasmOpenGLContext(const QSurfaceFormat &format) : m_requestedFormat(format) { m_requestedFormat.setRenderableType(QSurfaceFormat::OpenGLES); + + // if we set one, we need to set the other as well since in webgl, these are tied together + if (format.depthBufferSize() < 0 && format.stencilBufferSize() > 0) + m_requestedFormat.setDepthBufferSize(16); + + if (format.stencilBufferSize() < 0 && format.depthBufferSize() > 0) + m_requestedFormat.setStencilBufferSize(8); + } QWasmOpenGLContext::~QWasmOpenGLContext() @@ -91,10 +99,14 @@ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE QWasmOpenGLContext::createEmscriptenContext(cons attributes.majorVersion = 2; } + // WebGL doesn't allow separate attach buffers to STENCIL_ATTACHMENT and DEPTH_ATTACHMENT + // we need both or none + bool useDepthStencil = (format.depthBufferSize() > 0 || format.stencilBufferSize() > 0); + // WebGL offers enable/disable control but not size control for these attributes.alpha = format.alphaBufferSize() > 0; - attributes.depth = format.depthBufferSize() > 0; - attributes.stencil = format.stencilBufferSize() > 0; + attributes.depth = useDepthStencil; + attributes.stencil = useDepthStencil; EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context = emscripten_webgl_create_context(canvasId.toLocal8Bit().constData(), &attributes); diff --git a/src/plugins/platforms/wasm/wasm_shell.html b/src/plugins/platforms/wasm/wasm_shell.html index f7c856d63d..a118c217f3 100644 --- a/src/plugins/platforms/wasm/wasm_shell.html +++ b/src/plugins/platforms/wasm/wasm_shell.html @@ -3,7 +3,7 @@ <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <title>APPNAME</title> + <title>@APPNAME@</title> <style> html, body { padding: 0; margin : 0; overflow:hidden; height: 100% } /* the canvas *must not* have any border or padding, or mouse coords will be wrong */ @@ -18,7 +18,7 @@ <figure style="overflow:visible;" id="qtspinner"> <center style="margin-top:1.5em; line-height:150%"> <img src="qtlogo.svg"; width=320; height=200; style="display:block"> </img> - <strong>Qt for WebAssembly: APPNAME</strong> + <strong>Qt for WebAssembly: @APPNAME@</strong> <div id="qtstatus"></div> <noscript>JavaScript is disabled. Please enable JavaScript to use this application.</noscript> </center> @@ -57,7 +57,7 @@ canvas.style.display = 'block'; }, }); - qtLoader.loadEmscriptenModule("APPNAME"); + qtLoader.loadEmscriptenModule("@APPNAME@"); } </script> <script type="text/javascript" src="qtloader.js"></script> diff --git a/src/plugins/platforms/windows/qwindowscontext.cpp b/src/plugins/platforms/windows/qwindowscontext.cpp index f93d196b20..9be6d4ced7 100644 --- a/src/plugins/platforms/windows/qwindowscontext.cpp +++ b/src/plugins/platforms/windows/qwindowscontext.cpp @@ -1486,6 +1486,10 @@ void QWindowsContext::handleExitSizeMove(QWindow *window) keyboardModifiers); } } + if (d->m_systemInfo & QWindowsContext::SI_SupportsPointer) + d->m_pointerHandler.clearEvents(); + else + d->m_mouseHandler.clearEvents(); } bool QWindowsContext::asyncExpose() const diff --git a/src/plugins/platforms/windows/qwindowsmousehandler.cpp b/src/plugins/platforms/windows/qwindowsmousehandler.cpp index 5a52cd3ea8..97e1319e8d 100644 --- a/src/plugins/platforms/windows/qwindowsmousehandler.cpp +++ b/src/plugins/platforms/windows/qwindowsmousehandler.cpp @@ -157,6 +157,12 @@ QTouchDevice *QWindowsMouseHandler::ensureTouchDevice() return m_touchDevice; } +void QWindowsMouseHandler::clearEvents() +{ + m_lastEventType = QEvent::None; + m_lastEventButton = Qt::NoButton; +} + Qt::MouseButtons QWindowsMouseHandler::queryMouseButtons() { Qt::MouseButtons result = nullptr; @@ -293,8 +299,6 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd, Qt::MouseEventSource source = Qt::MouseEventNotSynthesized; - const MouseEvent mouseEvent = eventFromMsg(msg); - // Check for events synthesized from touch. Lower byte is touch index, 0 means pen. static const bool passSynthesizedMouseEvents = !(QWindowsIntegration::instance()->options() & QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch); @@ -311,13 +315,40 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd, } } + const Qt::KeyboardModifiers keyModifiers = QWindowsKeyMapper::queryKeyboardModifiers(); + const MouseEvent mouseEvent = eventFromMsg(msg); + Qt::MouseButtons buttons; + + if (mouseEvent.type >= QEvent::NonClientAreaMouseMove && mouseEvent.type <= QEvent::NonClientAreaMouseButtonDblClick) + buttons = queryMouseButtons(); + else + buttons = keyStateToMouseButtons(msg.wParam); + + // When the left/right mouse buttons are pressed over the window title bar + // WM_NCLBUTTONDOWN/WM_NCRBUTTONDOWN messages are received. But no UP + // messages are received on release, only WM_NCMOUSEMOVE/WM_MOUSEMOVE. + // We detect it and generate the missing release events here. (QTBUG-75678) + // The last event vars are cleared on QWindowsContext::handleExitSizeMove() + // to avoid generating duplicated release events. + if (m_lastEventType == QEvent::NonClientAreaMouseButtonPress + && (mouseEvent.type == QEvent::NonClientAreaMouseMove || mouseEvent.type == QEvent::MouseMove) + && (m_lastEventButton & buttons) == 0) { + if (mouseEvent.type == QEvent::NonClientAreaMouseMove) { + QWindowSystemInterface::handleFrameStrutMouseEvent(window, clientPosition, globalPosition, buttons, m_lastEventButton, + QEvent::NonClientAreaMouseButtonRelease, keyModifiers, source); + } else { + QWindowSystemInterface::handleMouseEvent(window, clientPosition, globalPosition, buttons, m_lastEventButton, + QEvent::MouseButtonRelease, keyModifiers, source); + } + } + m_lastEventType = mouseEvent.type; + m_lastEventButton = mouseEvent.button; + if (mouseEvent.type >= QEvent::NonClientAreaMouseMove && mouseEvent.type <= QEvent::NonClientAreaMouseButtonDblClick) { - const Qt::MouseButtons buttons = QWindowsMouseHandler::queryMouseButtons(); QWindowSystemInterface::handleFrameStrutMouseEvent(window, clientPosition, globalPosition, buttons, mouseEvent.button, mouseEvent.type, - QWindowsKeyMapper::queryKeyboardModifiers(), - source); + keyModifiers, source); return false; // Allow further event processing (dragging of windows). } @@ -340,7 +371,6 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd, } QWindowsWindow *platformWindow = static_cast<QWindowsWindow *>(window->handle()); - const Qt::MouseButtons buttons = keyStateToMouseButtons(int(msg.wParam)); // If the window was recently resized via mouse doubleclick on the frame or title bar, // we don't get WM_LBUTTONDOWN or WM_LBUTTONDBLCLK for the second click, @@ -467,8 +497,7 @@ bool QWindowsMouseHandler::translateMouseEvent(QWindow *window, HWND hwnd, if (!discardEvent && mouseEvent.type != QEvent::None) { QWindowSystemInterface::handleMouseEvent(window, winEventPosition, globalPosition, buttons, mouseEvent.button, mouseEvent.type, - QWindowsKeyMapper::queryKeyboardModifiers(), - source); + keyModifiers, source); } m_previousCaptureWindow = hasCapture ? window : nullptr; // QTBUG-48117, force synchronous handling for the extra buttons so that WM_APPCOMMAND diff --git a/src/plugins/platforms/windows/qwindowsmousehandler.h b/src/plugins/platforms/windows/qwindowsmousehandler.h index 480662c9bf..5fe4b09c1e 100644 --- a/src/plugins/platforms/windows/qwindowsmousehandler.h +++ b/src/plugins/platforms/windows/qwindowsmousehandler.h @@ -45,6 +45,7 @@ #include <QtCore/qpointer.h> #include <QtCore/qhash.h> +#include <QtGui/qevent.h> QT_BEGIN_NAMESPACE @@ -72,13 +73,14 @@ public: bool translateScrollEvent(QWindow *window, HWND hwnd, MSG msg, LRESULT *result); - static inline Qt::MouseButtons keyStateToMouseButtons(int); + static inline Qt::MouseButtons keyStateToMouseButtons(WPARAM); static inline Qt::KeyboardModifiers keyStateToModifiers(int); static inline int mouseButtonsToKeyState(Qt::MouseButtons); static Qt::MouseButtons queryMouseButtons(); QWindow *windowUnderMouse() const { return m_windowUnderMouse.data(); } void clearWindowUnderMouse() { m_windowUnderMouse = 0; } + void clearEvents(); private: inline bool translateMouseWheelEvent(QWindow *window, HWND hwnd, @@ -91,9 +93,11 @@ private: QTouchDevice *m_touchDevice = nullptr; bool m_leftButtonDown = false; QWindow *m_previousCaptureWindow = nullptr; + QEvent::Type m_lastEventType = QEvent::None; + Qt::MouseButton m_lastEventButton = Qt::NoButton; }; -Qt::MouseButtons QWindowsMouseHandler::keyStateToMouseButtons(int wParam) +Qt::MouseButtons QWindowsMouseHandler::keyStateToMouseButtons(WPARAM wParam) { Qt::MouseButtons mb(Qt::NoButton); if (wParam & MK_LBUTTON) diff --git a/src/plugins/platforms/windows/qwindowspointerhandler.cpp b/src/plugins/platforms/windows/qwindowspointerhandler.cpp index 0e686bfb10..778170d563 100644 --- a/src/plugins/platforms/windows/qwindowspointerhandler.cpp +++ b/src/plugins/platforms/windows/qwindowspointerhandler.cpp @@ -336,6 +336,12 @@ QTouchDevice *QWindowsPointerHandler::ensureTouchDevice() return m_touchDevice; } +void QWindowsPointerHandler::clearEvents() +{ + m_lastEventType = QEvent::None; + m_lastEventButton = Qt::NoButton; +} + void QWindowsPointerHandler::handleCaptureRelease(QWindow *window, QWindow *currentWindowUnderPointer, HWND hwnd, @@ -732,10 +738,35 @@ bool QWindowsPointerHandler::translateMouseEvent(QWindow *window, } const MouseEvent mouseEvent = eventFromMsg(msg); + Qt::MouseButtons mouseButtons; + + if (mouseEvent.type >= QEvent::NonClientAreaMouseMove && mouseEvent.type <= QEvent::NonClientAreaMouseButtonDblClick) + mouseButtons = queryMouseButtons(); + else + mouseButtons = mouseButtonsFromKeyState(msg.wParam); + + // When the left/right mouse buttons are pressed over the window title bar + // WM_NCLBUTTONDOWN/WM_NCRBUTTONDOWN messages are received. But no UP + // messages are received on release, only WM_NCMOUSEMOVE/WM_MOUSEMOVE. + // We detect it and generate the missing release events here. (QTBUG-75678) + // The last event vars are cleared on QWindowsContext::handleExitSizeMove() + // to avoid generating duplicated release events. + if (m_lastEventType == QEvent::NonClientAreaMouseButtonPress + && (mouseEvent.type == QEvent::NonClientAreaMouseMove || mouseEvent.type == QEvent::MouseMove) + && (m_lastEventButton & mouseButtons) == 0) { + if (mouseEvent.type == QEvent::NonClientAreaMouseMove) { + QWindowSystemInterface::handleFrameStrutMouseEvent(window, localPos, globalPos, mouseButtons, m_lastEventButton, + QEvent::NonClientAreaMouseButtonRelease, keyModifiers, source); + } else { + QWindowSystemInterface::handleMouseEvent(window, localPos, globalPos, mouseButtons, m_lastEventButton, + QEvent::MouseButtonRelease, keyModifiers, source); + } + } + m_lastEventType = mouseEvent.type; + m_lastEventButton = mouseEvent.button; if (mouseEvent.type >= QEvent::NonClientAreaMouseMove && mouseEvent.type <= QEvent::NonClientAreaMouseButtonDblClick) { - const Qt::MouseButtons nonclientButtons = queryMouseButtons(); - QWindowSystemInterface::handleFrameStrutMouseEvent(window, localPos, globalPos, nonclientButtons, + QWindowSystemInterface::handleFrameStrutMouseEvent(window, localPos, globalPos, mouseButtons, mouseEvent.button, mouseEvent.type, keyModifiers, source); return false; // Allow further event processing } @@ -751,8 +782,6 @@ bool QWindowsPointerHandler::translateMouseEvent(QWindow *window, return true; } - const Qt::MouseButtons mouseButtons = mouseButtonsFromKeyState(msg.wParam); - handleCaptureRelease(window, currentWindowUnderPointer, hwnd, mouseEvent.type, mouseButtons); handleEnterLeave(window, currentWindowUnderPointer, globalPos); diff --git a/src/plugins/platforms/windows/qwindowspointerhandler.h b/src/plugins/platforms/windows/qwindowspointerhandler.h index aebef062bc..ccbb1d3939 100644 --- a/src/plugins/platforms/windows/qwindowspointerhandler.h +++ b/src/plugins/platforms/windows/qwindowspointerhandler.h @@ -46,7 +46,7 @@ #include <QtCore/qpointer.h> #include <QtCore/qscopedpointer.h> #include <QtCore/qhash.h> -#include <qpa/qwindowsysteminterface.h> +#include <QtGui/qevent.h> QT_BEGIN_NAMESPACE @@ -64,6 +64,7 @@ public: QTouchDevice *ensureTouchDevice(); QWindow *windowUnderMouse() const { return m_windowUnderPointer.data(); } void clearWindowUnderMouse() { m_windowUnderPointer = nullptr; } + void clearEvents(); private: bool translateTouchEvent(QWindow *window, HWND hwnd, QtWindows::WindowsEventType et, MSG msg, PVOID vTouchInfo, unsigned int count); @@ -79,6 +80,8 @@ private: QPointer<QWindow> m_currentWindow; QWindow *m_previousCaptureWindow = nullptr; bool m_needsEnterOnPointerUpdate = false; + QEvent::Type m_lastEventType = QEvent::None; + Qt::MouseButton m_lastEventButton = Qt::NoButton; }; QT_END_NAMESPACE diff --git a/src/plugins/platforms/windows/uiautomation/qwindowsuiamainprovider.cpp b/src/plugins/platforms/windows/uiautomation/qwindowsuiamainprovider.cpp index 44328492a6..a427e553f0 100644 --- a/src/plugins/platforms/windows/uiautomation/qwindowsuiamainprovider.cpp +++ b/src/plugins/platforms/windows/uiautomation/qwindowsuiamainprovider.cpp @@ -52,6 +52,7 @@ #include "qwindowsuiatableitemprovider.h" #include "qwindowsuiagridprovider.h" #include "qwindowsuiagriditemprovider.h" +#include "qwindowsuiawindowprovider.h" #include "qwindowscombase.h" #include "qwindowscontext.h" #include "qwindowsuiautils.h" @@ -263,6 +264,11 @@ HRESULT QWindowsUiaMainProvider::GetPatternProvider(PATTERNID idPattern, IUnknow return UIA_E_ELEMENTNOTAVAILABLE; switch (idPattern) { + case UIA_WindowPatternId: + if (accessible->parent() && (accessible->parent()->role() == QAccessible::Application)) { + *pRetVal = new QWindowsUiaWindowProvider(id()); + } + break; case UIA_TextPatternId: case UIA_TextPattern2Id: // All text controls. @@ -352,8 +358,7 @@ HRESULT QWindowsUiaMainProvider::GetPropertyValue(PROPERTYID idProp, VARIANT *pR if (!accessible) return UIA_E_ELEMENTNOTAVAILABLE; - bool clientTopLevel = (accessible->role() == QAccessible::Client) - && accessible->parent() && (accessible->parent()->role() == QAccessible::Application); + bool topLevelWindow = accessible->parent() && (accessible->parent()->role() == QAccessible::Application); switch (idProp) { case UIA_ProcessIdPropertyId: @@ -379,7 +384,7 @@ HRESULT QWindowsUiaMainProvider::GetPropertyValue(PROPERTYID idProp, VARIANT *pR setVariantString(QStringLiteral("Qt"), pRetVal); break; case UIA_ControlTypePropertyId: - if (clientTopLevel) { + if (topLevelWindow) { // Reports a top-level widget as a window, instead of "custom". setVariantI4(UIA_WindowControlTypeId, pRetVal); } else { @@ -391,10 +396,20 @@ HRESULT QWindowsUiaMainProvider::GetPropertyValue(PROPERTYID idProp, VARIANT *pR setVariantString(accessible->text(QAccessible::Help), pRetVal); break; case UIA_HasKeyboardFocusPropertyId: - setVariantBool(accessible->state().focused, pRetVal); + if (topLevelWindow) { + // Windows set the active state to true when they are focused + setVariantBool(accessible->state().active, pRetVal); + } else { + setVariantBool(accessible->state().focused, pRetVal); + } break; case UIA_IsKeyboardFocusablePropertyId: - setVariantBool(accessible->state().focusable, pRetVal); + if (topLevelWindow) { + // Windows should always be focusable + setVariantBool(true, pRetVal); + } else { + setVariantBool(accessible->state().focusable, pRetVal); + } break; case UIA_IsOffscreenPropertyId: setVariantBool(accessible->state().offscreen, pRetVal); @@ -424,7 +439,7 @@ HRESULT QWindowsUiaMainProvider::GetPropertyValue(PROPERTYID idProp, VARIANT *pR break; case UIA_NamePropertyId: { QString name = accessible->text(QAccessible::Name); - if (name.isEmpty() && clientTopLevel) + if (name.isEmpty() && topLevelWindow) name = QCoreApplication::applicationName(); setVariantString(name, pRetVal); break; diff --git a/src/plugins/platforms/windows/uiautomation/qwindowsuiawindowprovider.cpp b/src/plugins/platforms/windows/uiautomation/qwindowsuiawindowprovider.cpp new file mode 100644 index 0000000000..3738aa72ff --- /dev/null +++ b/src/plugins/platforms/windows/uiautomation/qwindowsuiawindowprovider.cpp @@ -0,0 +1,168 @@ +/**************************************************************************** +** +** Copyright (C) 2019 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** 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. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtGui/qtguiglobal.h> +#if QT_CONFIG(accessibility) + +#include "qwindowsuiawindowprovider.h" +#include "qwindowsuiautils.h" +#include "qwindowscontext.h" + +#include <QtGui/qaccessible.h> +#include <QtGui/private/qwindow_p.h> +#include <QtCore/qloggingcategory.h> +#include <QtCore/qstring.h> + +QT_BEGIN_NAMESPACE + +using namespace QWindowsUiAutomation; + + +QWindowsUiaWindowProvider::QWindowsUiaWindowProvider(QAccessible::Id id) : + QWindowsUiaBaseProvider(id) +{ +} + +QWindowsUiaWindowProvider::~QWindowsUiaWindowProvider() +{ +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::SetVisualState(WindowVisualState state) { + qCDebug(lcQpaUiAutomation) << __FUNCTION__; + QAccessibleInterface *accessible = accessibleInterface(); + if (!accessible || !accessible->window()) + return UIA_E_ELEMENTNOTAVAILABLE; + auto window = accessible->window(); + switch (state) { + case WindowVisualState_Normal: + window->showNormal(); + break; + case WindowVisualState_Maximized: + window->showMaximized(); + break; + case WindowVisualState_Minimized: + window->showMinimized(); + break; + } + return S_OK; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::Close() { + qCDebug(lcQpaUiAutomation) << __FUNCTION__; + QAccessibleInterface *accessible = accessibleInterface(); + if (!accessible || !accessible->window()) + return UIA_E_ELEMENTNOTAVAILABLE; + accessible->window()->close(); + return S_OK; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::WaitForInputIdle(int milliseconds, __RPC__out BOOL *pRetVal) { + Q_UNUSED(milliseconds); + Q_UNUSED(pRetVal); + return UIA_E_NOTSUPPORTED; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::get_CanMaximize(__RPC__out BOOL *pRetVal) { + qCDebug(lcQpaUiAutomation) << __FUNCTION__; + QAccessibleInterface *accessible = accessibleInterface(); + if (!accessible || !accessible->window()) + return UIA_E_ELEMENTNOTAVAILABLE; + + auto window = accessible->window(); + auto flags = window->flags(); + + *pRetVal = (!(flags & Qt::MSWindowsFixedSizeDialogHint) + && (flags & Qt::WindowMaximizeButtonHint) + && ((flags & Qt::CustomizeWindowHint) + || window->maximumSize() == QSize(QWINDOWSIZE_MAX, QWINDOWSIZE_MAX))); + return S_OK; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::get_CanMinimize(__RPC__out BOOL *pRetVal) { + qCDebug(lcQpaUiAutomation) << __FUNCTION__; + QAccessibleInterface *accessible = accessibleInterface(); + if (!accessible || !accessible->window()) + return UIA_E_ELEMENTNOTAVAILABLE; + *pRetVal = accessible->window()->flags() & Qt::WindowMinimizeButtonHint; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::get_IsModal(__RPC__out BOOL *pRetVal) { + qCDebug(lcQpaUiAutomation) << __FUNCTION__; + QAccessibleInterface *accessible = accessibleInterface(); + if (!accessible || !accessible->window()) + return UIA_E_ELEMENTNOTAVAILABLE; + *pRetVal = accessible->window()->isModal(); + return S_OK; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::get_WindowVisualState(__RPC__out enum WindowVisualState *pRetVal) { + qCDebug(lcQpaUiAutomation) << __FUNCTION__; + QAccessibleInterface *accessible = accessibleInterface(); + if (!accessible || !accessible->window()) + return UIA_E_ELEMENTNOTAVAILABLE; + auto visibility = accessible->window()->visibility(); + switch (visibility) { + case QWindow::FullScreen: + case QWindow::Maximized: + *pRetVal = WindowVisualState_Maximized; + break; + case QWindow::Minimized: + *pRetVal = WindowVisualState_Minimized; + break; + default: + *pRetVal = WindowVisualState_Normal; + break; + } + return S_OK; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::get_WindowInteractionState(__RPC__out enum WindowInteractionState *pRetVal) { + Q_UNUSED(pRetVal); + return UIA_E_NOTSUPPORTED; +} + +HRESULT STDMETHODCALLTYPE QWindowsUiaWindowProvider::get_IsTopmost(__RPC__out BOOL *pRetVal) { + Q_UNUSED(pRetVal); + return UIA_E_NOTSUPPORTED; +} + +QT_END_NAMESPACE + +#endif // QT_CONFIG(accessibility) diff --git a/src/plugins/platforms/windows/uiautomation/qwindowsuiawindowprovider.h b/src/plugins/platforms/windows/uiautomation/qwindowsuiawindowprovider.h new file mode 100644 index 0000000000..343fb275f7 --- /dev/null +++ b/src/plugins/platforms/windows/uiautomation/qwindowsuiawindowprovider.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2019 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** 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. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QWINDOWSUIAWINDOWPROVIDER_H +#define QWINDOWSUIAWINDOWPROVIDER_H + +#include <QtGui/qtguiglobal.h> +#if QT_CONFIG(accessibility) + +#include "qwindowsuiabaseprovider.h" + +QT_BEGIN_NAMESPACE + +class QWindowsUiaWindowProvider : public QWindowsUiaBaseProvider, + public QWindowsComBase<IWindowProvider> +{ + Q_DISABLE_COPY(QWindowsUiaWindowProvider) +public: + explicit QWindowsUiaWindowProvider(QAccessible::Id id); + ~QWindowsUiaWindowProvider() override; + + HRESULT STDMETHODCALLTYPE SetVisualState(WindowVisualState state) override; + HRESULT STDMETHODCALLTYPE Close( void) override; + HRESULT STDMETHODCALLTYPE WaitForInputIdle(int milliseconds, __RPC__out BOOL *pRetVal) override; + HRESULT STDMETHODCALLTYPE get_CanMaximize(__RPC__out BOOL *pRetVal) override; + HRESULT STDMETHODCALLTYPE get_CanMinimize(__RPC__out BOOL *pRetVal) override; + HRESULT STDMETHODCALLTYPE get_IsModal(__RPC__out BOOL *pRetVal) override; + HRESULT STDMETHODCALLTYPE get_WindowVisualState(__RPC__out WindowVisualState *pRetVal) override; + HRESULT STDMETHODCALLTYPE get_WindowInteractionState(__RPC__out WindowInteractionState *pRetVal) override; + HRESULT STDMETHODCALLTYPE get_IsTopmost(__RPC__out BOOL *pRetVal) override; +}; + +QT_END_NAMESPACE + +#endif // QT_CONFIG(accessibility) + +#endif // QWINDOWSUIAWINDOWPROVIDER_H diff --git a/src/plugins/platforms/windows/uiautomation/uiautomation.pri b/src/plugins/platforms/windows/uiautomation/uiautomation.pri index b79e42cdec..ee9332e7ea 100644 --- a/src/plugins/platforms/windows/uiautomation/uiautomation.pri +++ b/src/plugins/platforms/windows/uiautomation/uiautomation.pri @@ -18,6 +18,7 @@ SOURCES += \ $$PWD/qwindowsuiatableitemprovider.cpp \ $$PWD/qwindowsuiagridprovider.cpp \ $$PWD/qwindowsuiagriditemprovider.cpp \ + $$PWD/qwindowsuiawindowprovider.cpp \ $$PWD/qwindowsuiautils.cpp HEADERS += \ @@ -37,6 +38,7 @@ HEADERS += \ $$PWD/qwindowsuiatableitemprovider.h \ $$PWD/qwindowsuiagridprovider.h \ $$PWD/qwindowsuiagriditemprovider.h \ + $$PWD/qwindowsuiawindowprovider.h \ $$PWD/qwindowsuiautils.h mingw: QMAKE_USE *= uuid diff --git a/src/plugins/platforms/winrt/qwinrttheme.cpp b/src/plugins/platforms/winrt/qwinrttheme.cpp index 283825a880..0e1504b1c1 100644 --- a/src/plugins/platforms/winrt/qwinrttheme.cpp +++ b/src/plugins/platforms/winrt/qwinrttheme.cpp @@ -44,6 +44,8 @@ #include <QtCore/qfunctions_winrt.h> #include <QtGui/QPalette> +#include <QtFontDatabaseSupport/private/qwinrtfontdatabase_p.h> + #include <wrl.h> #include <windows.ui.h> #include <windows.ui.viewmanagement.h> @@ -96,7 +98,13 @@ static IUISettings *uiSettings() class QWinRTThemePrivate { public: + QWinRTThemePrivate() + : monospaceFont(QWinRTFontDatabase::familyForStyleHint(QFont::Monospace)) + { + } + QPalette palette; + QFont monospaceFont; }; static inline QColor fromColor(const Color &color) @@ -321,4 +329,14 @@ const QPalette *QWinRTTheme::palette(Palette type) const return QPlatformTheme::palette(type); } +const QFont *QWinRTTheme::font(QPlatformTheme::Font type) const +{ + Q_D(const QWinRTTheme); + qCDebug(lcQpaTheme) << __FUNCTION__ << type; + if (type == QPlatformTheme::FixedFont) + return &d->monospaceFont; + + return QPlatformTheme::font(type); +} + QT_END_NAMESPACE diff --git a/src/plugins/platforms/winrt/qwinrttheme.h b/src/plugins/platforms/winrt/qwinrttheme.h index cc5fc851e7..acf5a54a94 100644 --- a/src/plugins/platforms/winrt/qwinrttheme.h +++ b/src/plugins/platforms/winrt/qwinrttheme.h @@ -58,6 +58,7 @@ public: QPlatformDialogHelper *createPlatformDialogHelper(DialogType type) const override; const QPalette *palette(Palette type = SystemPalette) const override; + const QFont *font(Font type = SystemFont) const override; static QVariant styleHint(QPlatformIntegration::StyleHint hint); QVariant themeHint(ThemeHint hint) const override; diff --git a/src/plugins/platforms/xcb/qxcbdrag.cpp b/src/plugins/platforms/xcb/qxcbdrag.cpp index aa329d8cb7..1ce947165d 100644 --- a/src/plugins/platforms/xcb/qxcbdrag.cpp +++ b/src/plugins/platforms/xcb/qxcbdrag.cpp @@ -202,7 +202,7 @@ void QXcbDrag::startDrag() if (connection()->mouseGrabber() == nullptr) shapedPixmapWindow()->setMouseGrabEnabled(true); - auto nativePixelPos = QHighDpi::toNativePixels(QCursor::pos(), initiatorWindow); + auto nativePixelPos = QHighDpi::toNativePixels(QCursor::pos(), initiatorWindow.data()); move(nativePixelPos, QGuiApplication::mouseButtons(), QGuiApplication::keyboardModifiers()); } diff --git a/src/plugins/styles/mac/qmacstyle_mac.mm b/src/plugins/styles/mac/qmacstyle_mac.mm index 3474e82c13..392368a40b 100644 --- a/src/plugins/styles/mac/qmacstyle_mac.mm +++ b/src/plugins/styles/mac/qmacstyle_mac.mm @@ -150,6 +150,16 @@ static QWindow *qt_getWindow(const QWidget *widget) QT_NAMESPACE_ALIAS_OBJC_CLASS(NotificationReceiver); @implementation NotificationReceiver +{ + QMacStylePrivate *privateStyle; +} + +- (instancetype)initWithPrivateStyle:(QMacStylePrivate *)style +{ + if (self = [super init]) + privateStyle = style; + return self; +} - (void)scrollBarStyleDidChange:(NSNotification *)notification { @@ -162,6 +172,23 @@ QT_NAMESPACE_ALIAS_OBJC_CLASS(NotificationReceiver); for (const auto &o : QMacStylePrivate::scrollBars) QCoreApplication::sendEvent(o, &event); } + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object + change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context +{ + Q_UNUSED(keyPath); + Q_UNUSED(object); + Q_UNUSED(change); + Q_UNUSED(context); + + Q_ASSERT([keyPath isEqualToString:@"effectiveAppearance"]); + Q_ASSERT(object == NSApp); + + for (NSView *b : privateStyle->cocoaControls) + [b release]; + privateStyle->cocoaControls.clear(); +} + @end @interface QT_MANGLE_NAMESPACE(QIndeterminateProgressIndicator) : NSProgressIndicator @@ -2068,11 +2095,17 @@ QMacStyle::QMacStyle() Q_D(QMacStyle); QMacAutoReleasePool pool; - d->receiver = [[NotificationReceiver alloc] init]; + d->receiver = [[NotificationReceiver alloc] initWithPrivateStyle:d]; [[NSNotificationCenter defaultCenter] addObserver:d->receiver selector:@selector(scrollBarStyleDidChange:) name:NSPreferredScrollerStyleDidChangeNotification object:nil]; +#if QT_MACOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__MAC_10_14) + if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::MacOSMojave) { + [NSApplication.sharedApplication addObserver:d->receiver forKeyPath:@"effectiveAppearance" + options:NSKeyValueObservingOptionNew context:nullptr]; + } +#endif } QMacStyle::~QMacStyle() @@ -2081,6 +2114,10 @@ QMacStyle::~QMacStyle() QMacAutoReleasePool pool; [[NSNotificationCenter defaultCenter] removeObserver:d->receiver]; +#if QT_MACOS_PLATFORM_SDK_EQUAL_OR_ABOVE(__MAC_10_14) + if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::MacOSMojave) + [NSApplication.sharedApplication removeObserver:d->receiver forKeyPath:@"effectiveAppearance"]; +#endif [d->receiver release]; } @@ -6129,8 +6166,9 @@ QSize QMacStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt, switch (ct) { #if QT_CONFIG(spinbox) case CT_SpinBox: - if (qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) { - const int buttonWidth = 20; // FIXME Use subControlRect() + if (const QStyleOptionSpinBox *vopt = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) { + const bool hasButtons = (vopt->buttonSymbols != QAbstractSpinBox::NoButtons); + const int buttonWidth = hasButtons ? proxy()->subControlRect(CC_SpinBox, vopt, SC_SpinBoxUp, widget).width() : 0; sz += QSize(buttonWidth, 0); } break; diff --git a/src/widgets/dialogs/qcolordialog.cpp b/src/widgets/dialogs/qcolordialog.cpp index 2911fc94ad..82c341b47c 100644 --- a/src/widgets/dialogs/qcolordialog.cpp +++ b/src/widgets/dialogs/qcolordialog.cpp @@ -1864,6 +1864,9 @@ void QColorDialogPrivate::_q_addCustom() void QColorDialogPrivate::retranslateStrings() { + if (nativeDialogInUse) + return; + if (!smallDisplay) { lblBasicColors->setText(QColorDialog::tr("&Basic colors")); lblCustomColors->setText(QColorDialog::tr("&Custom colors")); diff --git a/src/widgets/doc/snippets/cmake-macros/examples.cmake b/src/widgets/doc/snippets/cmake-macros/examples.cmake new file mode 100644 index 0000000000..61ec7aed54 --- /dev/null +++ b/src/widgets/doc/snippets/cmake-macros/examples.cmake @@ -0,0 +1,5 @@ +#! [qt5_wrap_ui] +set(SOURCES mainwindow.cpp main.cpp) +qt5_wrap_ui(SOURCES mainwindow.ui) +add_executable(myapp ${SOURCES}) +#! [qt5_wrap_ui] diff --git a/src/widgets/doc/src/cmake-macros.qdoc b/src/widgets/doc/src/cmake-macros.qdoc new file mode 100644 index 0000000000..36579576a9 --- /dev/null +++ b/src/widgets/doc/src/cmake-macros.qdoc @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** Copyright (C) 2019 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** 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. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: https://www.gnu.org/licenses/fdl-1.3.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! +\page qtwidgets-cmake-qt5-wrap-ui.html +\ingroup cmake-macros-qtwidgets + +\title qt5_wrap_ui + +\brief Creates sources for \c{.ui} files. + +\section1 Synopsis + +\badcode +qt5_wrap_ui(<VAR> ui_file1 [ui_file2 ...] + [OPTIONS ...]) +\endcode + +\section1 Description + +Creates rules for calling \l{uic}{User Interface Compiler (uic)} on the given +\c{.ui} files. For each input file, an header file is generated in the build +directory. The paths of the generated header files are added to\c{<VAR>}. + +\note This is a low-level macro. See the \l{CMake AUTOUIC Documentation} for a +more convenient way to process \c{.ui} files with \c{uic}. + +\section1 Options + +You can set additional \c{OPTIONS} that should be added to the \c{uic} calls. +You can find possible options in the \l{uic}{uic documentation}. + +\section1 Examples + +\snippet cmake-macros/examples.cmake qt5_wrap_ui +*/ diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp index 713f022bdd..65708fa1ca 100644 --- a/src/widgets/graphicsview/qgraphicsitem.cpp +++ b/src/widgets/graphicsview/qgraphicsitem.cpp @@ -9795,9 +9795,9 @@ QRectF QGraphicsPixmapItem::boundingRect() const return QRectF(); if (d->flags & ItemIsSelectable) { qreal pw = 1.0; - return QRectF(d->offset, d->pixmap.size() / d->pixmap.devicePixelRatio()).adjusted(-pw/2, -pw/2, pw/2, pw/2); + return QRectF(d->offset, QSizeF(d->pixmap.size()) / d->pixmap.devicePixelRatio()).adjusted(-pw/2, -pw/2, pw/2, pw/2); } else { - return QRectF(d->offset, d->pixmap.size() / d->pixmap.devicePixelRatio()); + return QRectF(d->offset, QSizeF(d->pixmap.size()) / d->pixmap.devicePixelRatio()); } } diff --git a/src/widgets/itemviews/qtreeview.cpp b/src/widgets/itemviews/qtreeview.cpp index 3fad6ca3df..55b10d13c1 100644 --- a/src/widgets/itemviews/qtreeview.cpp +++ b/src/widgets/itemviews/qtreeview.cpp @@ -1734,7 +1734,8 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, } // draw background for the branch (selection + alternate row) opt.rect = branches; - style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this); + if (style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, &opt, this)) + style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this); // draw background of the item (only alternate row). rest of the background // is provided by the delegate diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp index 2adbfeeb9b..8f927e8bee 100644 --- a/src/widgets/kernel/qwidget.cpp +++ b/src/widgets/kernel/qwidget.cpp @@ -2578,14 +2578,15 @@ void QWidgetPrivate::createWinId() /*! \internal Ensures that the widget is set on the screen point is on. This is handy getting a correct -size hint before a resize in e.g QMenu and QToolTip +size hint before a resize in e.g QMenu and QToolTip. +Returns if the screen was changed. */ -void QWidgetPrivate::setScreenForPoint(const QPoint &pos) +bool QWidgetPrivate::setScreenForPoint(const QPoint &pos) { Q_Q(QWidget); if (!q->isWindow()) - return; + return false; // Find the screen for pos and make the widget undertand it is on that screen. const QScreen *currentScreen = windowHandle() ? windowHandle()->screen() : nullptr; QScreen *actualScreen = QGuiApplication::screenAt(pos); @@ -2594,7 +2595,9 @@ void QWidgetPrivate::setScreenForPoint(const QPoint &pos) createWinId(); if (windowHandle()) windowHandle()->setScreen(actualScreen); + return true; } + return false; } /*! diff --git a/src/widgets/kernel/qwidget_p.h b/src/widgets/kernel/qwidget_p.h index 90c4c2a945..c073b8fb03 100644 --- a/src/widgets/kernel/qwidget_p.h +++ b/src/widgets/kernel/qwidget_p.h @@ -355,7 +355,7 @@ public: void createRecursively(); void createWinId(); - void setScreenForPoint(const QPoint &pos); + bool setScreenForPoint(const QPoint &pos); void createTLExtra(); void createExtra(); diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp index a3461d8848..35b630cde2 100644 --- a/src/widgets/styles/qcommonstyle.cpp +++ b/src/widgets/styles/qcommonstyle.cpp @@ -5029,7 +5029,8 @@ QSize QCommonStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt, case CT_SpinBox: if (const QStyleOptionSpinBox *vopt = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) { // Add button + frame widths - const int buttonWidth = (vopt->subControls & (QStyle::SC_SpinBoxUp | QStyle::SC_SpinBoxDown)) != 0 ? 20 : 0; + const bool hasButtons = (vopt->buttonSymbols != QAbstractSpinBox::NoButtons); + const int buttonWidth = hasButtons ? proxy()->subControlRect(CC_SpinBox, vopt, SC_SpinBoxUp, widget).width() : 0; const int fw = vopt->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, vopt, widget) : 0; sz += QSize(buttonWidth + 2*fw, 2*fw); } diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp index 0008f11546..bfc0496e8c 100644 --- a/src/widgets/styles/qstylesheetstyle.cpp +++ b/src/widgets/styles/qstylesheetstyle.cpp @@ -4992,17 +4992,19 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op switch (ct) { #if QT_CONFIG(spinbox) - case CT_SpinBox: // ### hopelessly broken QAbstractSpinBox (part 1) + case CT_SpinBox: if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) { - // Add some space for the up/down buttons - QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton); - if (subRule.hasDrawable()) { - QRect r = positionRect(w, rule, subRule, PseudoElement_SpinBoxUpButton, - opt->rect, opt->direction); - sz += QSize(r.width(), 0); - } else { - QSize defaultUpSize = defaultSize(w, subRule.size(), spinbox->rect, PseudoElement_SpinBoxUpButton); - sz += QSize(defaultUpSize.width(), 0); + if (spinbox->buttonSymbols != QAbstractSpinBox::NoButtons) { + // Add some space for the up/down buttons + QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton); + if (subRule.hasDrawable()) { + QRect r = positionRect(w, rule, subRule, PseudoElement_SpinBoxUpButton, + opt->rect, opt->direction); + sz.rwidth() += r.width(); + } else { + QSize defaultUpSize = defaultSize(w, subRule.size(), spinbox->rect, PseudoElement_SpinBoxUpButton); + sz.rwidth() += defaultUpSize.width(); + } } if (rule.hasBox() || rule.hasBorder() || !rule.hasNativeBorder()) sz = rule.boxSize(sz); @@ -5503,8 +5505,12 @@ QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComp : Qt::Alignment(Qt::AlignRight); downAlign = resolveAlignment(opt->direction, downAlign); - int upSize = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w).width(); - int downSize = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w).width(); + const bool hasButtons = (spin->buttonSymbols != QAbstractSpinBox::NoButtons); + const int upSize = hasButtons + ? subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w).width() : 0; + const int downSize = hasButtons + ? subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w).width() : 0; + int widestL = qMax((upAlign & Qt::AlignLeft) ? upSize : 0, (downAlign & Qt::AlignLeft) ? downSize : 0); int widestR = qMax((upAlign & Qt::AlignRight) ? upSize : 0, diff --git a/src/widgets/util/qcompleter.cpp b/src/widgets/util/qcompleter.cpp index 0daa4a4b41..e41f7e7573 100644 --- a/src/widgets/util/qcompleter.cpp +++ b/src/widgets/util/qcompleter.cpp @@ -976,18 +976,48 @@ void QCompleterPrivate::showPopup(const QRect& rect) popup->show(); } +#if QT_CONFIG(filesystemmodel) +static bool isRoot(const QFileSystemModel *model, const QString &path) +{ + const auto index = model->index(path); + return index.isValid() && model->fileInfo(index).isRoot(); +} + +static bool completeOnLoaded(const QFileSystemModel *model, + const QString &nativePrefix, + const QString &path, + Qt::CaseSensitivity caseSensitivity) +{ + const auto pathSize = path.size(); + const auto prefixSize = nativePrefix.size(); + if (prefixSize < pathSize) + return false; + const QString prefix = QDir::fromNativeSeparators(nativePrefix); + if (prefixSize == pathSize) + return path.compare(prefix, caseSensitivity) == 0 && isRoot(model, path); + // The user is typing something within that directory and is not in a subdirectory yet. + const auto separator = QLatin1Char('/'); + return prefix.startsWith(path, caseSensitivity) && prefix.at(pathSize) == separator + && !prefix.rightRef(prefixSize - pathSize - 1).contains(separator); +} + void QCompleterPrivate::_q_fileSystemModelDirectoryLoaded(const QString &path) { Q_Q(QCompleter); // Slot called when QFileSystemModel has finished loading. // If we hide the popup because there was no match because the model was not loaded yet, - // we re-start the completion when we get the results - if (hiddenBecauseNoMatch - && prefix.startsWith(path) && prefix != (path + QLatin1Char('/')) - && widget) { - q->complete(); + // we re-start the completion when we get the results (unless triggered by + // something else, see QTBUG-14292). + if (hiddenBecauseNoMatch && widget) { + if (auto model = qobject_cast<const QFileSystemModel *>(proxy->sourceModel())) { + if (completeOnLoaded(model, prefix, path, cs)) + q->complete(); + } } } +#else // QT_CONFIG(filesystemmodel) +void QCompleterPrivate::_q_fileSystemModelDirectoryLoaded(const QString &) {} +#endif /*! Constructs a completer object with the given \a parent. diff --git a/src/widgets/widgets/qabstractspinbox.cpp b/src/widgets/widgets/qabstractspinbox.cpp index e99bb8e907..04276aa400 100644 --- a/src/widgets/widgets/qabstractspinbox.cpp +++ b/src/widgets/widgets/qabstractspinbox.cpp @@ -212,6 +212,7 @@ void QAbstractSpinBox::setButtonSymbols(ButtonSymbols buttonSymbols) if (d->buttonSymbols != buttonSymbols) { d->buttonSymbols = buttonSymbols; d->updateEditFieldGeometry(); + updateGeometry(); update(); } } diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp index 14964a696d..287be3e272 100644 --- a/src/widgets/widgets/qmenu.cpp +++ b/src/widgets/widgets/qmenu.cpp @@ -73,6 +73,7 @@ #endif #include "qpushbutton.h" #include "qtooltip.h" +#include <qwindow.h> #include <private/qpushbutton_p.h> #include <private/qaction_p.h> #include <private/qguiapplication_p.h> @@ -1485,6 +1486,8 @@ void QMenuPrivate::_q_platformMenuAboutToShow() { Q_Q(QMenu); + emit q->aboutToShow(); + #ifdef Q_OS_OSX if (platformMenu) { const auto actions = q->actions(); @@ -1498,8 +1501,6 @@ void QMenuPrivate::_q_platformMenuAboutToShow() } } #endif - - emit q->aboutToShow(); } bool QMenuPrivate::hasMouseMoved(const QPoint &globalPos) @@ -2328,8 +2329,10 @@ void QMenu::popup(const QPoint &p, QAction *atAction) d->motions = 0; d->doChildEffects = true; d->updateLayoutDirection(); - // Ensure that we get correct sizeHints by placing this window on the right screen. - d->setScreenForPoint(p); + + // Ensure that we get correct sizeHints by placing this window on the correct screen. + if (d->setScreenForPoint(p)) + d->itemsDirty = true; const bool contextMenu = d->isContextMenu(); if (d->lastContextMenu != contextMenu) { diff --git a/src/widgets/widgets/qwidgetresizehandler.cpp b/src/widgets/widgets/qwidgetresizehandler.cpp index 7ed6f6d78d..e8d435429f 100644 --- a/src/widgets/widgets/qwidgetresizehandler.cpp +++ b/src/widgets/widgets/qwidgetresizehandler.cpp @@ -121,7 +121,7 @@ bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee) break; const QRect widgetRect = widget->rect().marginsAdded(QMargins(range, range, range, range)); const QPoint cursorPoint = widget->mapFromGlobal(e->globalPos()); - if (!widgetRect.contains(cursorPoint) || mode == Nowhere) + if (!widgetRect.contains(cursorPoint)) return false; if (e->button() == Qt::LeftButton) { #if 0 // Used to be included in Qt4 for Q_WS_X11 diff --git a/src/winmain/qtmain_winrt.cpp b/src/winmain/qtmain_winrt.cpp index 7cc57f4d46..1828c4ca16 100644 --- a/src/winmain/qtmain_winrt.cpp +++ b/src/winmain/qtmain_winrt.cpp @@ -317,23 +317,26 @@ private: if (quote) break; commandLine[i] = '\0'; - if (args.last()[0] != '\0') + if (!args.isEmpty() && args.last() && args.last()[0] != '\0') args.append(commandLine.data() + i + 1); // fall through default: - if (args.last()[0] == '\0') + if (!args.isEmpty() && args.last() && args.last()[0] == '\0') args.last() = commandLine.data() + i; escape = false; // only quotes are escaped break; } } - if (args.count() >= 2 && strncmp(args.at(1), "-ServerName:", 12) == 0) + if (args.count() >= 2 && args.at(1) && strncmp(args.at(1), "-ServerName:", 12) == 0) args.remove(1); bool develMode = false; bool debugWait = false; for (int i = args.count() - 1; i >= 0; --i) { + if (!args.at(i)) + continue; + const char *arg = args.at(i); if (strcmp(arg, "-qdevel") == 0) { develMode = true; diff --git a/src/xml/doc/src/qtxml-index.qdoc b/src/xml/doc/src/qtxml-index.qdoc index dfb9b45fa7..65c6673db0 100644 --- a/src/xml/doc/src/qtxml-index.qdoc +++ b/src/xml/doc/src/qtxml-index.qdoc @@ -30,8 +30,10 @@ \title Qt XML \brief The Qt XML module provides C++ implementations of the SAX and DOM standards for XML. - The module is not actively maintained anymore. Please use - the QXmlStreamReader and QXmlStreamWriter classes in Qt Core instead. + Note that the module will not receive additional features anymore. For reading or writing XML + documents iteratively (SAX), we recommend using Qt Core's QXmlStreamReader and + QXmlStreamWriter classes. The classes are both easier to use and more compliant with the + XML standard. To include the definitions of the module's classes, use the following directive: diff --git a/src/xml/doc/src/qtxml.qdoc b/src/xml/doc/src/qtxml.qdoc index ad9b08b623..452e39d745 100644 --- a/src/xml/doc/src/qtxml.qdoc +++ b/src/xml/doc/src/qtxml.qdoc @@ -33,8 +33,10 @@ \brief The Qt XML module provides C++ implementations of the SAX and DOM standards for XML. - The module is not actively maintained anymore. Please use - the \l{QXmlStreamReader} and \l{QXmlStreamWriter} classes in \l{Qt Core} instead. + Note that the module will not receive additional features anymore. For reading or writing XML + documents iteratively (SAX), we recommend using Qt Core's QXmlStreamReader and + QXmlStreamWriter classes. The classes are both easier to use and more compliant with the + XML standard. To include the definitions of the module's classes, use the following directive: diff --git a/tests/auto/corelib/global/qfloat16/tst_qfloat16.cpp b/tests/auto/corelib/global/qfloat16/tst_qfloat16.cpp index 6894fd4cc3..0848a4160f 100644 --- a/tests/auto/corelib/global/qfloat16/tst_qfloat16.cpp +++ b/tests/auto/corelib/global/qfloat16/tst_qfloat16.cpp @@ -174,7 +174,9 @@ void tst_qfloat16::qNan() QVERIFY(qIsInf(-inf)); QVERIFY(qIsInf(2.f*inf)); QVERIFY(qIsInf(inf*2.f)); - QCOMPARE(qfloat16(1.f/inf), qfloat16(0.f)); + // QTBUG-75812: QEMU's over-optimized arm64 flakily fails 1/inf == 0 :-( + if (qfloat16(9.785e-4f) == qfloat16(9.794e-4f)) + QCOMPARE(qfloat16(1.f/inf), qfloat16(0.f)); #ifdef Q_CC_INTEL QEXPECT_FAIL("", "ICC optimizes zero * anything to zero", Continue); #endif diff --git a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp index 64075a94f0..0944ec252e 100644 --- a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp +++ b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp @@ -655,6 +655,8 @@ void tst_QFileInfo::canonicalFilePath() QVERIFY(tempFile.open(QFile::WriteOnly)); QFileInfo fi(tempFile.fileName()); QCOMPARE(fi.canonicalFilePath(), QDir::currentPath() + "/" + fileName); + fi = QFileInfo(tempFile.fileName() + QString::fromLatin1("/")); + QCOMPARE(fi.canonicalFilePath(), QString::fromLatin1("")); tempFile.remove(); // This used to crash on Mac, verify that it doesn't anymore. diff --git a/tests/auto/corelib/tools/qstringapisymmetry/tst_qstringapisymmetry.cpp b/tests/auto/corelib/tools/qstringapisymmetry/tst_qstringapisymmetry.cpp index 3062c09db3..7e5a855552 100644 --- a/tests/auto/corelib/tools/qstringapisymmetry/tst_qstringapisymmetry.cpp +++ b/tests/auto/corelib/tools/qstringapisymmetry/tst_qstringapisymmetry.cpp @@ -1203,7 +1203,7 @@ void tst_QStringApiSymmetry::trimmed_data() for (int len = 0; len < latin1Whitespace.size(); ++len) { for (int pos = 0; pos < latin1Whitespace.size() - len; ++pos) { const QString unicode = latin1Whitespace.mid(pos, len) + str + latin1Whitespace.mid(pos, len); - const QScopedPointer<const char> escaped(QTest::toString(unicode)); + const QScopedArrayPointer<const char> escaped(QTest::toString(unicode)); QTest::addRow("%s", escaped.data()) << unicode << QStringRef(&str); } } diff --git a/tests/auto/gui/kernel/qwindow/BLACKLIST b/tests/auto/gui/kernel/qwindow/BLACKLIST index caf39742f6..1820499a53 100644 --- a/tests/auto/gui/kernel/qwindow/BLACKLIST +++ b/tests/auto/gui/kernel/qwindow/BLACKLIST @@ -17,6 +17,8 @@ android [modalWindowEnterEventOnHide_QTBUG35109] ubuntu-16.04 osx ci +[spuriousMouseMove] +windows ci # QTBUG-69162 android [modalDialogClosingOneOfTwoModal] diff --git a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp index 9415908383..4f26950192 100644 --- a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp +++ b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp @@ -45,10 +45,6 @@ # include <QtCore/qt_windows.h> #endif -// For QSignalSpy slot connections. -Q_DECLARE_METATYPE(Qt::ScreenOrientation) -Q_DECLARE_METATYPE(QWindow::Visibility) - static bool isPlatformWinRT() { static const bool isWinRT = !QGuiApplication::platformName().compare(QLatin1String("winrt"), Qt::CaseInsensitive); @@ -185,7 +181,7 @@ void tst_QWindow::setParent() QVERIFY2(c.children().contains(&d), "Parent should have child in list of children"); a.create(); - b.setParent(0); + b.setParent(nullptr); QVERIFY2(!b.handle(), "Making window top level shouild not automatically create it"); QWindow e; @@ -228,7 +224,7 @@ void tst_QWindow::setVisible() f.setVisible(true); QVERIFY(!f.handle()); QVERIFY(!e.handle()); - f.setParent(0); + f.setParent(nullptr); QVERIFY2(f.handle(), "Making a visible but not created child window top level should create it"); QVERIFY(QTest::qWaitForWindowExposed(&f)); @@ -304,7 +300,7 @@ public: m_framePositionsOnMove.clear(); } - bool event(QEvent *event) + bool event(QEvent *event) override { m_received[event->type()]++; m_order << event->type(); @@ -323,6 +319,7 @@ public: case QEvent::WindowStateChange: lastReceivedWindowState = windowState(); + break; default: break; @@ -363,7 +360,7 @@ private: class ColoredWindow : public QRasterWindow { public: - explicit ColoredWindow(const QColor &color, QWindow *parent = 0) : QRasterWindow(parent), m_color(color) {} + explicit ColoredWindow(const QColor &color, QWindow *parent = nullptr) : QRasterWindow(parent), m_color(color) {} void paintEvent(QPaintEvent *) override { QPainter p(this); @@ -381,6 +378,7 @@ void tst_QWindow::eventOrderOnShow() QRect geometry(m_availableTopLeft + QPoint(80, 80), m_testWindowSize); Window window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(geometry); window.show(); QCoreApplication::processEvents(); @@ -440,12 +438,12 @@ void tst_QWindow::exposeEventOnShrink_QTBUG54040() void tst_QWindow::positioning_data() { - QTest::addColumn<int>("windowflags"); + QTest::addColumn<Qt::WindowFlags>("windowflags"); - QTest::newRow("default") << int(Qt::Window | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint); + QTest::newRow("default") << (Qt::Window | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint); -#ifdef Q_OS_OSX - QTest::newRow("fake") << int(Qt::Window | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); +#ifdef Q_OS_MACOS + QTest::newRow("fake") << (Qt::Window | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); #endif } @@ -500,8 +498,8 @@ void tst_QWindow::positioning() // events, so set the width to suitably large value to avoid those. const QRect geometry(m_availableTopLeft + QPoint(80, 80), m_testWindowSize); - QFETCH(int, windowflags); - Window window((Qt::WindowFlags)windowflags); + QFETCH(Qt::WindowFlags, windowflags); + Window window(windowflags); window.setGeometry(QRect(m_availableTopLeft + QPoint(20, 20), m_testWindowSize)); window.setFramePosition(m_availableTopLeft + QPoint(40, 40)); // Move window around before show, size must not change. QCOMPARE(window.geometry().size(), m_testWindowSize); @@ -628,14 +626,12 @@ void tst_QWindow::childWindowPositioning() QFETCH(bool, showInsteadOfCreate); - QWindow* windows[] = { &topLevelWindowFirst, &childWindowAfter, &childWindowFirst, &topLevelWindowAfter, 0 }; - for (int i = 0; windows[i]; ++i) { - QWindow *window = windows[i]; - if (showInsteadOfCreate) { + QWindow *windows[] = {&topLevelWindowFirst, &childWindowAfter, &childWindowFirst, &topLevelWindowAfter}; + for (QWindow *window : windows) { + if (showInsteadOfCreate) window->showNormal(); - } else { + else window->create(); - } } if (showInsteadOfCreate) { @@ -712,7 +708,7 @@ void tst_QWindow::stateChange() // explicitly use non-fullscreen show. show() can be fullscreen on some platforms window.showNormal(); QVERIFY(QTest::qWaitForWindowExposed(&window)); - foreach (Qt::WindowState state, stateSequence) { + for (Qt::WindowState state : qAsConst(stateSequence)) { window.setWindowState(state); QCoreApplication::processEvents(); } @@ -726,15 +722,9 @@ class PlatformWindowFilter : public QObject { Q_OBJECT public: - PlatformWindowFilter(QObject *parent = 0) - : QObject(parent) - , m_window(nullptr) - , m_alwaysExisted(true) - {} - - void setWindow(Window *window) { m_window = window; } + explicit PlatformWindowFilter(Window *window) : m_window(window) {} - bool eventFilter(QObject *o, QEvent *e) + bool eventFilter(QObject *o, QEvent *e) override { // Check that the platform surface events are delivered synchronously. // If they are, the native platform surface should always exist when we @@ -749,7 +739,7 @@ public: private: Window *m_window; - bool m_alwaysExisted; + bool m_alwaysExisted = true; }; void tst_QWindow::platformSurface() @@ -757,8 +747,7 @@ void tst_QWindow::platformSurface() QRect geometry(m_availableTopLeft + QPoint(80, 80), m_testWindowSize); Window window; - PlatformWindowFilter filter; - filter.setWindow(&window); + PlatformWindowFilter filter(&window); window.installEventFilter(&filter); window.setGeometry(geometry); @@ -784,6 +773,7 @@ void tst_QWindow::isExposed() QRect geometry(m_availableTopLeft + QPoint(80, 80), m_testWindowSize); Window window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(geometry); QCOMPARE(window.geometry(), geometry); window.show(); @@ -818,6 +808,7 @@ void tst_QWindow::isActive() QSKIP("QWindow::requestActivate() is not supported."); Window window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); // Some platforms enforce minimum widths for windows, which can cause extra resize // events, so set the width to suitably large value to avoid those. window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); @@ -916,13 +907,16 @@ void tst_QWindow::isActive() class InputTestWindow : public ColoredWindow { public: - void keyPressEvent(QKeyEvent *event) { + void keyPressEvent(QKeyEvent *event) override + { keyPressCode = event->key(); } - void keyReleaseEvent(QKeyEvent *event) { + void keyReleaseEvent(QKeyEvent *event) override + { keyReleaseCode = event->key(); } - void mousePressEvent(QMouseEvent *event) { + void mousePressEvent(QMouseEvent *event) override + { if (ignoreMouse) { event->ignore(); } else { @@ -935,7 +929,8 @@ public: QCoreApplication::processEvents(); } } - void mouseReleaseEvent(QMouseEvent *event) { + void mouseReleaseEvent(QMouseEvent *event) override + { if (ignoreMouse) { event->ignore(); } else { @@ -944,7 +939,8 @@ public: mouseReleaseButton = event->button(); } } - void mouseMoveEvent(QMouseEvent *event) { + void mouseMoveEvent(QMouseEvent *event) override + { buttonStateInGeneratedMove = event->buttons(); if (ignoreMouse) { event->ignore(); @@ -954,7 +950,8 @@ public: mouseMoveScreenPos = event->screenPos(); } } - void mouseDoubleClickEvent(QMouseEvent *event) { + void mouseDoubleClickEvent(QMouseEvent *event) override + { if (ignoreMouse) { event->ignore(); } else { @@ -962,7 +959,8 @@ public: mouseSequenceSignature += 'd'; } } - void touchEvent(QTouchEvent *event) { + void touchEvent(QTouchEvent *event) override + { if (ignoreTouch) { event->ignore(); return; @@ -987,7 +985,8 @@ public: } } } - bool event(QEvent *e) { + bool event(QEvent *e) override + { switch (e->type()) { case QEvent::Enter: ++enterEventCount; @@ -998,37 +997,31 @@ public: default: break; } - return QWindow::event(e); + return ColoredWindow::event(e); } - void resetCounters() { + void resetCounters() + { mousePressedCount = mouseReleasedCount = mouseMovedCount = mouseDoubleClickedCount = 0; - mouseSequenceSignature = QString(); + mouseSequenceSignature.clear(); touchPressedCount = touchReleasedCount = touchMovedCount = 0; enterEventCount = leaveEventCount = 0; } explicit InputTestWindow(const QColor &color = Qt::white, QWindow *parent = nullptr) - : ColoredWindow(color, parent) - { - keyPressCode = keyReleaseCode = 0; - mousePressButton = mouseReleaseButton = mouseMoveButton = 0; - ignoreMouse = ignoreTouch = false; - spinLoopWhenPressed = false; - resetCounters(); - } + : ColoredWindow(color, parent) {} - int keyPressCode, keyReleaseCode; - int mousePressButton, mouseReleaseButton, mouseMoveButton; - int mousePressedCount, mouseReleasedCount, mouseMovedCount, mouseDoubleClickedCount; + int keyPressCode = 0, keyReleaseCode = 0; + int mousePressButton = 0, mouseReleaseButton = 0, mouseMoveButton = 0; + int mousePressedCount = 0, mouseReleasedCount = 0, mouseMovedCount = 0, mouseDoubleClickedCount = 0; QString mouseSequenceSignature; QPointF mousePressScreenPos, mouseMoveScreenPos, mousePressLocalPos; - int touchPressedCount, touchReleasedCount, touchMovedCount; - QEvent::Type touchEventType; - int enterEventCount, leaveEventCount; + int touchPressedCount = 0, touchReleasedCount = 0, touchMovedCount = 0; + QEvent::Type touchEventType = QEvent::None; + int enterEventCount = 0, leaveEventCount = 0; - bool ignoreMouse, ignoreTouch; + bool ignoreMouse = false, ignoreTouch = false; - bool spinLoopWhenPressed; + bool spinLoopWhenPressed = false; Qt::MouseButtons buttonStateInGeneratedMove; }; @@ -1073,15 +1066,15 @@ void tst_QWindow::testInputEvents() window.mousePressButton = window.mouseReleaseButton = 0; const QPointF nonWindowGlobal(window.geometry().topRight() + QPoint(200, 50)); // not inside the window const QPointF deviceNonWindowGlobal = QHighDpi::toNativePixels(nonWindowGlobal, window.screen()); - QWindowSystemInterface::handleMouseEvent(0, deviceNonWindowGlobal, deviceNonWindowGlobal, Qt::LeftButton); - QWindowSystemInterface::handleMouseEvent(0, deviceNonWindowGlobal, deviceNonWindowGlobal, Qt::NoButton); + QWindowSystemInterface::handleMouseEvent(nullptr, deviceNonWindowGlobal, deviceNonWindowGlobal, Qt::LeftButton); + QWindowSystemInterface::handleMouseEvent(nullptr, deviceNonWindowGlobal, deviceNonWindowGlobal, Qt::NoButton); QCoreApplication::processEvents(); QCOMPARE(window.mousePressButton, 0); QCOMPARE(window.mouseReleaseButton, 0); const QPointF windowGlobal = window.mapToGlobal(local.toPoint()); const QPointF deviceWindowGlobal = QHighDpi::toNativePixels(windowGlobal, window.screen()); - QWindowSystemInterface::handleMouseEvent(0, deviceWindowGlobal, deviceWindowGlobal, Qt::LeftButton); - QWindowSystemInterface::handleMouseEvent(0, deviceWindowGlobal, deviceWindowGlobal, Qt::NoButton); + QWindowSystemInterface::handleMouseEvent(nullptr, deviceWindowGlobal, deviceWindowGlobal, Qt::LeftButton); + QWindowSystemInterface::handleMouseEvent(nullptr, deviceWindowGlobal, deviceWindowGlobal, Qt::NoButton); QCoreApplication::processEvents(); QCOMPARE(window.mousePressButton, int(Qt::LeftButton)); QCOMPARE(window.mouseReleaseButton, int(Qt::LeftButton)); @@ -1092,6 +1085,7 @@ void tst_QWindow::testInputEvents() void tst_QWindow::touchToMouseTranslation() { InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.ignoreTouch = true; window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); @@ -1145,7 +1139,7 @@ void tst_QWindow::touchToMouseTranslation() QTRY_COMPARE(window.mousePressButton, 0); QTRY_COMPARE(window.mouseReleaseButton, 0); - qApp->setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, false); + QCoreApplication::setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, false); window.ignoreTouch = true; points[0].state = Qt::TouchPointPressed; @@ -1156,7 +1150,7 @@ void tst_QWindow::touchToMouseTranslation() QWindowSystemInterface::handleTouchEvent(&window, touchDevice, points); QCoreApplication::processEvents(); - qApp->setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, true); + QCoreApplication::setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, true); // mouse event synthesizing disabled QTRY_COMPARE(window.mousePressButton, 0); @@ -1166,6 +1160,7 @@ void tst_QWindow::touchToMouseTranslation() void tst_QWindow::touchToMouseTranslationForDevices() { InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.ignoreTouch = true; window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); @@ -1194,9 +1189,10 @@ void tst_QWindow::touchToMouseTranslationForDevices() void tst_QWindow::mouseToTouchTranslation() { - qApp->setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); + QCoreApplication::setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.ignoreMouse = true; window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); @@ -1206,12 +1202,12 @@ void tst_QWindow::mouseToTouchTranslation() QWindowSystemInterface::handleMouseEvent(&window, QPoint(10, 10), window.mapToGlobal(QPoint(10, 10)), Qt::NoButton); QCoreApplication::processEvents(); - qApp->setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false); + QCoreApplication::setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false); QTRY_COMPARE(window.touchPressedCount, 1); QTRY_COMPARE(window.touchReleasedCount, 1); - qApp->setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); + QCoreApplication::setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); window.ignoreMouse = false; @@ -1219,7 +1215,7 @@ void tst_QWindow::mouseToTouchTranslation() QWindowSystemInterface::handleMouseEvent(&window, QPoint(10, 10), window.mapToGlobal(QPoint(10, 10)), Qt::NoButton); QCoreApplication::processEvents(); - qApp->setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false); + QCoreApplication::setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false); // no new touch events should be generated since the input window handles the mouse events QTRY_COMPARE(window.touchPressedCount, 1); @@ -1241,10 +1237,12 @@ void tst_QWindow::mouseToTouchTranslation() void tst_QWindow::mouseToTouchLoop() { // make sure there's no infinite loop when synthesizing both ways - qApp->setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); - qApp->setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, true); + QCoreApplication::setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); + QCoreApplication::setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, true); InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); + window.ignoreMouse = true; window.ignoreTouch = true; window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); @@ -1255,13 +1253,14 @@ void tst_QWindow::mouseToTouchLoop() QWindowSystemInterface::handleMouseEvent(&window, QPoint(10, 10), window.mapToGlobal(QPoint(10, 10)), Qt::NoButton); QCoreApplication::processEvents(); - qApp->setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false); - qApp->setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, true); + QCoreApplication::setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false); + QCoreApplication::setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, true); } void tst_QWindow::touchCancel() { InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); QVERIFY(QTest::qWaitForWindowExposed(&window)); @@ -1321,6 +1320,7 @@ void tst_QWindow::touchCancel() void tst_QWindow::touchCancelWithTouchToMouse() { InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.ignoreTouch = true; window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); @@ -1343,7 +1343,7 @@ void tst_QWindow::touchCancelWithTouchToMouse() // Cancel the touch. Should result in a mouse release for windows that have // have an active touch-to-mouse sequence. - QWindowSystemInterface::handleTouchCancelEvent(0, touchDevice); + QWindowSystemInterface::handleTouchCancelEvent(nullptr, touchDevice); QCoreApplication::processEvents(); QTRY_COMPARE(window.mouseReleaseButton, int(Qt::LeftButton)); @@ -1358,7 +1358,7 @@ void tst_QWindow::touchCancelWithTouchToMouse() QTRY_COMPARE(window.mousePressButton, 0); // Cancel the touch. It should not result in a mouse release with this window. - QWindowSystemInterface::handleTouchCancelEvent(0, touchDevice); + QWindowSystemInterface::handleTouchCancelEvent(nullptr, touchDevice); QCoreApplication::processEvents(); QTRY_COMPARE(window.mouseReleaseButton, 0); } @@ -1369,6 +1369,7 @@ void tst_QWindow::touchInterruptedByPopup() QSKIP("Wayland: This test crashes with xdg-shell unstable v6"); InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); QVERIFY(QTest::qWaitForWindowExposed(&window)); @@ -1489,6 +1490,7 @@ void tst_QWindow::sizes() void tst_QWindow::close() { QWindow a; + a.setTitle(QLatin1String(QTest::currentTestFunction())); QWindow b; QWindow c(&a); @@ -1506,8 +1508,9 @@ void tst_QWindow::activateAndClose() if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::WindowActivation)) QSKIP("QWindow::requestActivate() is not supported."); - for (int i = 0; i < 10; ++i) { + for (int i = 0; i < 10; ++i) { QWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction()) + QString::number(i)); #if defined(Q_OS_QNX) window.setSurfaceType(QSurface::OpenGLSurface); #endif @@ -1525,15 +1528,16 @@ void tst_QWindow::activateAndClose() #endif window.requestActivate(); QVERIFY(QTest::qWaitForWindowActive(&window)); - QCOMPARE(qGuiApp->focusWindow(), &window); + QCOMPARE(QGuiApplication::focusWindow(), &window); } } void tst_QWindow::mouseEventSequence() { - int doubleClickInterval = qGuiApp->styleHints()->mouseDoubleClickInterval(); + const auto doubleClickInterval = ulong(QGuiApplication::styleHints()->mouseDoubleClickInterval()); InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); window.show(); QVERIFY(QTest::qWaitForWindowExposed(&window)); @@ -1655,6 +1659,7 @@ void tst_QWindow::windowModality() void tst_QWindow::inputReentrancy() { InputTestWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.spinLoopWhenPressed = true; window.setGeometry(QRect(m_availableTopLeft + QPoint(80, 80), m_testWindowSize)); @@ -1700,17 +1705,20 @@ void tst_QWindow::inputReentrancy() class TabletTestWindow : public QWindow { public: - TabletTestWindow() : eventType(QEvent::None) { } - void tabletEvent(QTabletEvent *ev) { + void tabletEvent(QTabletEvent *ev) override + { eventType = ev->type(); eventGlobal = ev->globalPosF(); eventLocal = ev->posF(); eventDevice = ev->device(); } - QEvent::Type eventType; + + QEvent::Type eventType = QEvent::None; QPointF eventGlobal, eventLocal; - int eventDevice; - bool eventFilter(QObject *obj, QEvent *ev) { + int eventDevice = -1; + + bool eventFilter(QObject *obj, QEvent *ev) override + { if (ev->type() == QEvent::TabletEnterProximity || ev->type() == QEvent::TabletLeaveProximity) { eventType = ev->type(); @@ -1758,6 +1766,7 @@ void tst_QWindow::tabletEvents() void tst_QWindow::windowModality_QTBUG27039() { QWindow parent; + parent.setTitle(QLatin1String(QTest::currentTestFunction())); parent.setGeometry(QRect(m_availableTopLeft + QPoint(10, 10), m_testWindowSize)); parent.show(); @@ -1868,6 +1877,7 @@ void tst_QWindow::initialSize() QSize defaultSize(0,0); { Window w; + w.setTitle(QLatin1String(QTest::currentTestFunction())); w.showNormal(); QTRY_VERIFY(w.width() > 0); QTRY_VERIFY(w.height() > 0); @@ -1875,6 +1885,7 @@ void tst_QWindow::initialSize() } { Window w; + w.setTitle(QLatin1String(QTest::currentTestFunction())); w.setWidth(m_testWindowSize.width()); w.showNormal(); if (isPlatformWinRT()) @@ -1884,6 +1895,7 @@ void tst_QWindow::initialSize() } { Window w; + w.setTitle(QLatin1String(QTest::currentTestFunction())); const QSize testSize(m_testWindowSize.width(), 42); w.resize(testSize); w.showNormal(); @@ -1910,6 +1922,7 @@ void tst_QWindow::modalDialog() QSKIP("Test fails due to QTBUG-61965, and is slow due to QTBUG-61964"); QWindow normalWindow; + normalWindow.setTitle(QLatin1String(QTest::currentTestFunction())); normalWindow.setFramePosition(m_availableTopLeft + QPoint(80, 80)); normalWindow.resize(m_testWindowSize); normalWindow.show(); @@ -1945,6 +1958,7 @@ void tst_QWindow::modalDialogClosingOneOfTwoModal() QSKIP("QWindow::requestActivate() is not supported."); QWindow normalWindow; + normalWindow.setTitle(QLatin1String(QTest::currentTestFunction())); normalWindow.setFramePosition(m_availableTopLeft + QPoint(80, 80)); normalWindow.resize(m_testWindowSize); normalWindow.show(); @@ -1992,6 +2006,7 @@ void tst_QWindow::modalWithChildWindow() QSKIP("QWindow::requestActivate() is not supported."); QWindow normalWindow; + normalWindow.setTitle(QLatin1String(QTest::currentTestFunction())); normalWindow.setFramePosition(m_availableTopLeft + QPoint(80, 80)); normalWindow.resize(m_testWindowSize); normalWindow.show(); @@ -2028,6 +2043,7 @@ void tst_QWindow::modalWindowModallity() QSKIP("QWindow::requestActivate() is not supported."); QWindow normal_window; + normal_window.setTitle(QLatin1String(QTest::currentTestFunction())); normal_window.setFramePosition(m_availableTopLeft + QPoint(80, 80)); normal_window.resize(m_testWindowSize); normal_window.show(); @@ -2058,6 +2074,7 @@ void tst_QWindow::modalWindowModallity() void tst_QWindow::modalWindowPosition() { QWindow window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(QRect(m_availableTopLeft + QPoint(100, 100), m_testWindowSize)); // Allow for any potential resizing due to constraints QRect origGeo = window.geometry(); @@ -2341,6 +2358,7 @@ void tst_QWindow::requestUpdate() QRect geometry(m_availableTopLeft + QPoint(80, 80), m_testWindowSize); Window window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(geometry); window.show(); QCoreApplication::processEvents(); @@ -2370,10 +2388,10 @@ void tst_QWindow::flags() class EventWindow : public QWindow { public: - EventWindow() : QWindow(), gotBlocked(false) {} - bool gotBlocked; + bool gotBlocked = false; + protected: - bool event(QEvent *e) + bool event(QEvent *e) override { if (e->type() == QEvent::WindowBlocked) gotBlocked = true; @@ -2384,6 +2402,7 @@ protected: void tst_QWindow::testBlockingWindowShownAfterModalDialog() { EventWindow normalWindow; + normalWindow.setTitle(QLatin1String(QTest::currentTestFunction())); normalWindow.setFramePosition(m_availableTopLeft + QPoint(80, 80)); normalWindow.resize(m_testWindowSize); normalWindow.show(); @@ -2411,6 +2430,7 @@ void tst_QWindow::testBlockingWindowShownAfterModalDialog() void tst_QWindow::generatedMouseMove() { InputTestWindow w; + w.setTitle(QLatin1String(QTest::currentTestFunction())); w.setGeometry(QRect(m_availableTopLeft + QPoint(100, 100), m_testWindowSize)); w.setFlags(w.flags() | Qt::FramelessWindowHint); // ### FIXME: QTBUG-63542 w.show(); @@ -2422,34 +2442,34 @@ void tst_QWindow::generatedMouseMove() QTest::mouseMove(&w, point); QVERIFY(w.mouseMovedCount == 1); // A press event that does not change position should not generate mouse move - QTest::mousePress(&w, Qt::LeftButton, 0, point); - QTest::mousePress(&w, Qt::RightButton, 0, point); + QTest::mousePress(&w, Qt::LeftButton, Qt::KeyboardModifiers(), point); + QTest::mousePress(&w, Qt::RightButton, Qt::KeyboardModifiers(), point); QVERIFY(w.mouseMovedCount == 1); // Verify that a move event is generated for a mouse release event that changes position point += step; - QTest::mouseRelease(&w, Qt::LeftButton, 0, point); + QTest::mouseRelease(&w, Qt::LeftButton,Qt::KeyboardModifiers(), point); QVERIFY(w.mouseMovedCount == 2); QVERIFY(w.buttonStateInGeneratedMove == (Qt::LeftButton | Qt::RightButton)); point += step; - QTest::mouseRelease(&w, Qt::RightButton, 0, point); + QTest::mouseRelease(&w, Qt::RightButton, Qt::KeyboardModifiers(), point); QVERIFY(w.mouseMovedCount == 3); QVERIFY(w.buttonStateInGeneratedMove == Qt::RightButton); // Verify that a move event is generated for a mouse press event that changes position point += step; - QTest::mousePress(&w, Qt::LeftButton, 0, point); + QTest::mousePress(&w, Qt::LeftButton, Qt::KeyboardModifiers(), point); QVERIFY(w.mouseMovedCount == 4); QVERIFY(w.buttonStateInGeneratedMove == Qt::NoButton); point += step; - QTest::mousePress(&w, Qt::RightButton, 0, point); + QTest::mousePress(&w, Qt::RightButton, Qt::KeyboardModifiers(), point); QVERIFY(w.mouseMovedCount == 5); QVERIFY(w.buttonStateInGeneratedMove == Qt::LeftButton); // A release event that does not change position should not generate mouse move - QTest::mouseRelease(&w, Qt::RightButton, 0, point); - QTest::mouseRelease(&w, Qt::LeftButton, 0, point); + QTest::mouseRelease(&w, Qt::RightButton, Qt::KeyboardModifiers(), point); + QTest::mouseRelease(&w, Qt::LeftButton, Qt::KeyboardModifiers(), point); QVERIFY(w.mouseMovedCount == 5); } @@ -2458,6 +2478,7 @@ void tst_QWindow::keepPendingUpdateRequests() QRect geometry(m_availableTopLeft + QPoint(80, 80), m_testWindowSize); Window window; + window.setTitle(QLatin1String(QTest::currentTestFunction())); window.setGeometry(geometry); window.show(); QCoreApplication::processEvents(); diff --git a/tests/auto/gui/text/qfontdatabase/BLACKLIST b/tests/auto/gui/text/qfontdatabase/BLACKLIST index 7f479e4b0e..0870ca11d7 100644 --- a/tests/auto/gui/text/qfontdatabase/BLACKLIST +++ b/tests/auto/gui/text/qfontdatabase/BLACKLIST @@ -1,3 +1,2 @@ [systemFixedFont] # QTBUG-54623 -winrt b2qt diff --git a/tests/auto/widgets/kernel/qapplication/modal/base.cpp b/tests/auto/widgets/kernel/qapplication/modal/base.cpp index 19f8abebbd..249d402f2e 100644 --- a/tests/auto/widgets/kernel/qapplication/modal/base.cpp +++ b/tests/auto/widgets/kernel/qapplication/modal/base.cpp @@ -32,9 +32,8 @@ base::base(QWidget *parent) : QWidget(parent) { m_timer = new QTimer(this); - m_modalStarted = false; m_timer->setSingleShot(false); - connect(m_timer, SIGNAL(timeout()), this, SLOT(periodicTimer())); + connect(m_timer, &QTimer::timeout, this, &base::periodicTimer); m_timer->start(5000); } @@ -43,6 +42,7 @@ void base::periodicTimer() if(m_modalStarted) exit(0); m_modalDialog = new QDialog(this); + m_modalDialog->setWindowTitle(QLatin1String("modal")); m_modalDialog->setModal(true); m_modalDialog->show(); m_modalStarted = true; diff --git a/tests/auto/widgets/kernel/qapplication/modal/base.h b/tests/auto/widgets/kernel/qapplication/modal/base.h index 95eb427e61..153d9ca420 100644 --- a/tests/auto/widgets/kernel/qapplication/modal/base.h +++ b/tests/auto/widgets/kernel/qapplication/modal/base.h @@ -37,12 +37,10 @@ class base : public QWidget { Q_OBJECT QTimer *m_timer; - bool m_modalStarted; - QDialog *m_modalDialog; + bool m_modalStarted = false; + QDialog *m_modalDialog = nullptr; public: - explicit base(QWidget *parent = 0); - -signals: + explicit base(QWidget *parent = nullptr); public slots: void periodicTimer(); diff --git a/tests/auto/widgets/kernel/qapplication/modal/main.cpp b/tests/auto/widgets/kernel/qapplication/modal/main.cpp index 400792637f..9dcb6732fa 100644 --- a/tests/auto/widgets/kernel/qapplication/modal/main.cpp +++ b/tests/auto/widgets/kernel/qapplication/modal/main.cpp @@ -26,8 +26,6 @@ ** ****************************************************************************/ -#include <QtGui> - #include <QApplication> #include "base.h" @@ -35,7 +33,6 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); QApplication::setAttribute(Qt::AA_NativeWindows); //QTBUG-15774 - base *b = new base(); - Q_UNUSED(b); + base b; return app.exec(); } diff --git a/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp b/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp index af70b653ee..4f94e83c1c 100644 --- a/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp +++ b/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp @@ -27,7 +27,6 @@ ****************************************************************************/ -//#define QT_TST_QAPP_DEBUG #include <qdebug.h> #include <QtTest/QtTest> @@ -55,35 +54,14 @@ #include <QtWidgets/QStyle> #include <qpa/qwindowsysteminterface.h> +#include <qpa/qwindowsysteminterface_p.h> #include <private/qhighdpiscaling_p.h> -QT_BEGIN_NAMESPACE -static QWindowSystemInterface::TouchPoint touchPoint(const QTouchEvent::TouchPoint& pt) -{ - QWindowSystemInterface::TouchPoint p; - p.id = pt.id(); - p.flags = pt.flags(); - p.normalPosition = pt.normalizedPos(); - p.area = pt.screenRect(); - p.pressure = pt.pressure(); - p.state = pt.state(); - p.velocity = pt.velocity(); - p.rawPositions = pt.rawScreenPositions(); - return p; -} - -static QList<struct QWindowSystemInterface::TouchPoint> touchPointList(const QList<QTouchEvent::TouchPoint>& pointList) -{ - QList<struct QWindowSystemInterface::TouchPoint> newList; - - Q_FOREACH (QTouchEvent::TouchPoint p, pointList) - { - newList.append(touchPoint(p)); - } - return newList; -} +#include <algorithm> +Q_LOGGING_CATEGORY(lcTests, "qt.widgets.tests") +QT_BEGIN_NAMESPACE extern bool Q_GUI_EXPORT qt_tab_all_widgets(); // from qapplication.cpp QT_END_NAMESPACE @@ -92,9 +70,6 @@ class tst_QApplication : public QObject { Q_OBJECT -public: - tst_QApplication(); - private slots: void cleanup(); void sendEventsOnProcessEvents(); // this must be the first test @@ -165,12 +140,6 @@ private slots: void settableStyleHints_data(); void settableStyleHints(); // Needs to run last as it changes style hints. - -protected slots: - void quitApplication(); - -private: - bool quitApplicationTriggered; }; class EventSpy : public QObject @@ -179,7 +148,7 @@ class EventSpy : public QObject public: QList<int> recordedEvents; - bool eventFilter(QObject *, QEvent *event) + bool eventFilter(QObject *, QEvent *event) override { recordedEvents.append(event->type()); return false; @@ -189,7 +158,7 @@ public: void tst_QApplication::sendEventsOnProcessEvents() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); EventSpy spy; app.installEventFilter(&spy); @@ -203,14 +172,10 @@ void tst_QApplication::sendEventsOnProcessEvents() class CloseEventTestWindow : public QWidget { public: - CloseEventTestWindow(QWidget *parent = 0) - : QWidget(parent) - { - } - - void closeEvent(QCloseEvent *event) + void closeEvent(QCloseEvent *event) override { QWidget dialog; + dialog.setWindowTitle(QLatin1String("CloseEventTestWindow")); dialog.show(); dialog.close(); @@ -220,11 +185,6 @@ public: static char *argv0; -tst_QApplication::tst_QApplication() - : quitApplicationTriggered(false) -{ -} - void tst_QApplication::cleanup() { // TODO: Add cleanup code here. @@ -260,13 +220,12 @@ void tst_QApplication::staticSetup() class TestApplication : public QApplication { public: - TestApplication( int &argc, char **argv ) - : QApplication( argc, argv) + TestApplication(int &argc, char **argv) : QApplication( argc, argv) { - startTimer( 150 ); + startTimer(150); } - void timerEvent( QTimerEvent * ) + void timerEvent(QTimerEvent *) override { quit(); } @@ -278,24 +237,26 @@ void tst_QApplication::alert() QSKIP("WinRT does not support more than 1 native widget at the same time"); #endif int argc = 0; - QApplication app(argc, 0); - app.alert(0, 0); + QApplication app(argc, nullptr); + QApplication::alert(nullptr, 0); QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget widget2; - app.alert(&widget, 100); + widget2.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('2')); + QApplication::alert(&widget, 100); widget.show(); widget2.show(); QVERIFY(QTest::qWaitForWindowExposed(&widget)); QVERIFY(QTest::qWaitForWindowExposed(&widget2)); - app.alert(&widget, -1); - app.alert(&widget, 250); + QApplication::alert(&widget, -1); + QApplication::alert(&widget, 250); widget2.activateWindow(); QApplication::setActiveWindow(&widget2); - app.alert(&widget, 0); + QApplication::alert(&widget, 0); widget.activateWindow(); QApplication::setActiveWindow(&widget); - app.alert(&widget, 200); + QApplication::alert(&widget, 200); } void tst_QApplication::multiple_data() @@ -316,7 +277,7 @@ void tst_QApplication::multiple() int i = 0; int argc = 0; while (i++ < 5) { - TestApplication app(argc, 0); + TestApplication app(argc, nullptr); if (features.contains("QFont")) { // create font and force loading @@ -332,7 +293,7 @@ void tst_QApplication::multiple() QWidget widget; } - QVERIFY(!app.exec()); + QVERIFY(!QCoreApplication::exec()); } } @@ -344,7 +305,7 @@ void tst_QApplication::nonGui() #endif int argc = 0; - QApplication app(argc, 0, false); + QApplication app(argc, nullptr, false); QCOMPARE(qApp, &app); } @@ -355,36 +316,29 @@ void tst_QApplication::setFont_data() QTest::addColumn<bool>("beforeAppConstructor"); int argc = 0; - QApplication app(argc, 0); // Needed for QFontDatabase + QApplication app(argc, nullptr); // Needed for QFontDatabase - int cnt = 0; QFontDatabase fdb; - QStringList families = fdb.families(); - for (QStringList::const_iterator itr = families.cbegin(); - itr != families.cend(); - ++itr) { - if (cnt < 3) { - QString family = *itr; - QStringList styles = fdb.styles(family); - if (styles.size() > 0) { - QString style = styles.first(); - QList<int> sizes = fdb.pointSizes(family, style); - if (!sizes.size()) - sizes = fdb.standardSizes(); - if (sizes.size() > 0) { - const QByteArray cntB = QByteArray::number(cnt); - QTest::newRow(("data" + cntB + "a").constData()) - << family - << sizes.first() - << false; - QTest::newRow(("data" + cntB + "b").constData()) - << family - << sizes.first() - << true; - } + const QStringList &families = fdb.families(); + for (int i = 0, count = qMin(3, families.size()); i < count; ++i) { + const auto &family = families.at(i); + const QStringList &styles = fdb.styles(family); + if (!styles.isEmpty()) { + QList<int> sizes = fdb.pointSizes(family, styles.constFirst()); + if (sizes.isEmpty()) + sizes = QFontDatabase::standardSizes(); + if (!sizes.isEmpty()) { + const QByteArray name = QByteArrayLiteral("data") + QByteArray::number(i); + QTest::newRow((name + 'a').constData()) + << family + << sizes.constFirst() + << false; + QTest::newRow((name + 'b').constData()) + << family + << sizes.constFirst() + << true; } } - ++cnt; } QTest::newRow("nonexistingfont after") << "nosuchfont_probably_quiteunlikely" @@ -412,7 +366,7 @@ void tst_QApplication::setFont() } int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); if (!beforeAppConstructor) QApplication::setFont( font ); @@ -436,31 +390,30 @@ void tst_QApplication::args_data() void tst_QApplication::task109149() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); QApplication::setFont(QFont("helvetica", 100)); QWidget w; w.setWindowTitle("hello"); w.show(); - app.processEvents(); + QCoreApplication::processEvents(); } -static char ** QString2cstrings( const QString &args ) +static char **QString2cstrings(const QString &args) { - static QList<QByteArray> cache; + static QByteArrayList cache; - int i; - char **argarray = 0; - QStringList list = args.split(' ');; - argarray = new char*[list.count()+1]; + const auto &list = args.splitRef(' '); + auto argarray = new char*[list.count() + 1]; - for (i = 0; i < (int)list.count(); ++i ) { + int i = 0; + for (; i < list.size(); ++i ) { QByteArray l1 = list[i].toLatin1(); argarray[i] = l1.data(); cache.append(l1); } - argarray[i] = 0; + argarray[i] = nullptr; return argarray; } @@ -498,13 +451,13 @@ void tst_QApplication::args() delete [] argv; // Make sure we switch back to native style. - QApplicationPrivate::styleOverride = QString(); + QApplicationPrivate::styleOverride.clear(); } void tst_QApplication::appName() { char argv0[] = "tst_qapplication"; - char *argv[] = { argv0, 0 }; + char *argv[] = { argv0, nullptr }; int argc = 1; QApplication app(argc, argv); QCOMPARE(::qAppName(), QString::fromLatin1("tst_qapplication")); @@ -521,7 +474,7 @@ public: } protected: - void timerEvent(QTimerEvent *) + void timerEvent(QTimerEvent *) override { close(); } @@ -531,22 +484,24 @@ protected: void tst_QApplication::lastWindowClosed() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); - QSignalSpy spy(&app, SIGNAL(lastWindowClosed())); + QSignalSpy spy(&app, &QGuiApplication::lastWindowClosed); QPointer<QDialog> dialog = new QDialog; + dialog->setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("Dialog")); QVERIFY(dialog->testAttribute(Qt::WA_QuitOnClose)); - QTimer::singleShot(1000, dialog, SLOT(accept())); + QTimer::singleShot(1000, dialog, &QDialog::accept); dialog->exec(); QVERIFY(dialog); QCOMPARE(spy.count(), 0); QPointer<CloseWidget>widget = new CloseWidget; + widget->setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("CloseWidget")); QVERIFY(widget->testAttribute(Qt::WA_QuitOnClose)); widget->show(); - QObject::connect(&app, SIGNAL(lastWindowClosed()), widget, SLOT(deleteLater())); - app.exec(); + QObject::connect(&app, &QGuiApplication::lastWindowClosed, widget.data(), &QObject::deleteLater); + QCoreApplication::exec(); QVERIFY(!widget); QCOMPARE(spy.count(), 1); spy.clear(); @@ -555,14 +510,17 @@ void tst_QApplication::lastWindowClosed() // show 3 windows, close them, should only get lastWindowClosed once QWidget w1; + w1.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('1')); QWidget w2; + w1.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('2')); QWidget w3; + w1.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('3')); w1.show(); w2.show(); w3.show(); - QTimer::singleShot(1000, &app, SLOT(closeAllWindows())); - app.exec(); + QTimer::singleShot(1000, &app, &QApplication::closeAllWindows); + QCoreApplication::exec(); QCOMPARE(spy.count(), 1); } @@ -570,27 +528,27 @@ class QuitOnLastWindowClosedDialog : public QDialog { Q_OBJECT public: - QPushButton *okButton; - QuitOnLastWindowClosedDialog() { QHBoxLayout *hbox = new QHBoxLayout(this); - okButton = new QPushButton("&ok", this); + m_okButton = new QPushButton("&ok", this); - hbox->addWidget(okButton); - connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); - connect(okButton, SIGNAL(clicked()), this, SLOT(ok_clicked())); + hbox->addWidget(m_okButton); + connect(m_okButton, &QAbstractButton::clicked, this, &QDialog::accept); + connect(m_okButton, &QAbstractButton::clicked, this, &QuitOnLastWindowClosedDialog::ok_clicked); } public slots: + void animateOkClick() { m_okButton->animateClick(); } + void ok_clicked() { QDialog other; QTimer timer; - connect(&timer, SIGNAL(timeout()), &other, SLOT(accept())); - QSignalSpy spy(&timer, SIGNAL(timeout())); - QSignalSpy appSpy(qApp, SIGNAL(lastWindowClosed())); + connect(&timer, &QTimer::timeout, &other, &QDialog::accept); + QSignalSpy spy(&timer, &QTimer::timeout); + QSignalSpy appSpy(qApp, &QGuiApplication::lastWindowClosed); timer.start(1000); other.exec(); @@ -599,6 +557,9 @@ public slots: QCOMPARE(spy.count(), 1); QCOMPARE(appSpy.count(), 1); } + +private: + QPushButton *m_okButton; }; class QuitOnLastWindowClosedWindow : public QWidget @@ -606,16 +567,16 @@ class QuitOnLastWindowClosedWindow : public QWidget Q_OBJECT public: - QuitOnLastWindowClosedWindow() - { } + QuitOnLastWindowClosedWindow() = default; public slots: void execDialogThenShow() { QDialog dialog; + dialog.setWindowTitle(QLatin1String("QuitOnLastWindowClosedWindow Dialog")); QTimer timer1; - connect(&timer1, SIGNAL(timeout()), &dialog, SLOT(accept())); - QSignalSpy spy1(&timer1, SIGNAL(timeout())); + connect(&timer1, &QTimer::timeout, &dialog, &QDialog::accept); + QSignalSpy spy1(&timer1, &QTimer::timeout); timer1.setSingleShot(true); timer1.start(1000); dialog.exec(); @@ -629,27 +590,29 @@ void tst_QApplication::quitOnLastWindowClosed() { { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); QuitOnLastWindowClosedDialog d; + d.setWindowTitle(QLatin1String(QTest::currentTestFunction())); d.show(); - QTimer::singleShot(1000, d.okButton, SLOT(animateClick())); + QTimer::singleShot(1000, &d, &QuitOnLastWindowClosedDialog::animateOkClick); - QSignalSpy appSpy(&app, SIGNAL(lastWindowClosed())); - app.exec(); + QSignalSpy appSpy(&app, &QGuiApplication::lastWindowClosed); + QCoreApplication::exec(); // lastWindowClosed() signal should only be sent after the last dialog is closed QCOMPARE(appSpy.count(), 2); } { int argc = 0; - QApplication app(argc, 0); - QSignalSpy appSpy(&app, SIGNAL(lastWindowClosed())); + QApplication app(argc, nullptr); + QSignalSpy appSpy(&app, &QGuiApplication::lastWindowClosed); QDialog dialog; + dialog.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QTimer timer1; - connect(&timer1, SIGNAL(timeout()), &dialog, SLOT(accept())); - QSignalSpy spy1(&timer1, SIGNAL(timeout())); + connect(&timer1, &QTimer::timeout, &dialog, &QDialog::accept); + QSignalSpy spy1(&timer1, &QTimer::timeout); timer1.setSingleShot(true); timer1.start(1000); dialog.exec(); @@ -657,26 +620,28 @@ void tst_QApplication::quitOnLastWindowClosed() QCOMPARE(appSpy.count(), 0); QTimer timer2; - connect(&timer2, SIGNAL(timeout()), &app, SLOT(quit())); - QSignalSpy spy2(&timer2, SIGNAL(timeout())); + connect(&timer2, &QTimer::timeout, &app, &QCoreApplication::quit); + QSignalSpy spy2(&timer2, &QTimer::timeout); timer2.setSingleShot(true); timer2.start(1000); - int returnValue = app.exec(); + int returnValue = QCoreApplication::exec(); QCOMPARE(returnValue, 0); QCOMPARE(spy2.count(), 1); QCOMPARE(appSpy.count(), 0); } { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); QTimer timer; timer.setInterval(100); - QSignalSpy spy(&app, SIGNAL(aboutToQuit())); - QSignalSpy spy2(&timer, SIGNAL(timeout())); + QSignalSpy spy(&app, &QCoreApplication::aboutToQuit); + QSignalSpy spy2(&timer, &QTimer::timeout); QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QDialog *dialog = new QDialog(&mainWindow); + dialog->setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("Dialog")); QVERIFY(app.quitOnLastWindowClosed()); QVERIFY(mainWindow.testAttribute(Qt::WA_QuitOnClose)); @@ -688,21 +653,29 @@ void tst_QApplication::quitOnLastWindowClosed() QVERIFY(QTest::qWaitForWindowExposed(dialog)); timer.start(); - QTimer::singleShot(1000, &mainWindow, SLOT(close())); // This should quit the application - QTimer::singleShot(2000, &app, SLOT(quit())); // This makes sure we quit even if it didn't + QTimer::singleShot(1000, &mainWindow, &QWidget::close); // This should quit the application + QTimer::singleShot(2000, &app, &QCoreApplication::quit); // This makes sure we quit even if it didn't - app.exec(); + QCoreApplication::exec(); QCOMPARE(spy.count(), 1); QVERIFY(spy2.count() < 15); // Should be around 10 if closing caused the quit } + + bool quitApplicationTriggered = false; + auto quitSlot = [&quitApplicationTriggered] () { + quitApplicationTriggered = true; + QCoreApplication::quit(); + }; + { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); - QSignalSpy spy(&app, SIGNAL(aboutToQuit())); + QSignalSpy spy(&app, &QCoreApplication::aboutToQuit); CloseEventTestWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QVERIFY(app.quitOnLastWindowClosed()); QVERIFY(mainWindow.testAttribute(Qt::WA_QuitOnClose)); @@ -710,30 +683,31 @@ void tst_QApplication::quitOnLastWindowClosed() mainWindow.show(); QVERIFY(QTest::qWaitForWindowExposed(&mainWindow)); - QTimer::singleShot(1000, &mainWindow, SLOT(close())); // This should NOT quit the application (see CloseEventTestWindow) + QTimer::singleShot(1000, &mainWindow, &QWidget::close); // This should NOT quit the application (see CloseEventTestWindow) quitApplicationTriggered = false; - QTimer::singleShot(2000, this, SLOT(quitApplication())); // This actually quits the application. + QTimer::singleShot(2000, this, quitSlot); // This actually quits the application. - app.exec(); + QCoreApplication::exec(); QCOMPARE(spy.count(), 1); QVERIFY(quitApplicationTriggered); } { int argc = 0; - QApplication app(argc, 0); - QSignalSpy appSpy(&app, SIGNAL(lastWindowClosed())); + QApplication app(argc, nullptr); + QSignalSpy appSpy(&app, &QApplication::lastWindowClosed); // exec a dialog for 1 second, then show the window QuitOnLastWindowClosedWindow window; - QTimer::singleShot(0, &window, SLOT(execDialogThenShow())); + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); + QTimer::singleShot(0, &window, &QuitOnLastWindowClosedWindow::execDialogThenShow); QTimer timer; - QSignalSpy timerSpy(&timer, SIGNAL(timeout())); - connect(&timer, SIGNAL(timeout()), &window, SLOT(close())); + QSignalSpy timerSpy(&timer, &QTimer::timeout); + connect(&timer, &QTimer::timeout, &window, &QWidget::close); timer.setSingleShot(true); timer.start(2000); - int returnValue = app.exec(); + int returnValue = QCoreApplication::exec(); QCOMPARE(returnValue, 0); // failure here means the timer above didn't fire, and the // quit was caused the dialog being closed (not the window) @@ -742,34 +716,38 @@ void tst_QApplication::quitOnLastWindowClosed() } { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); QVERIFY(app.quitOnLastWindowClosed()); QWindow w; + w.setTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("Window")); w.show(); QWidget wid; + wid.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("Widget")); wid.show(); - QTimer::singleShot(1000, &wid, SLOT(close())); // This should NOT quit the application because the + QTimer::singleShot(1000, &wid, &QWidget::close); // This should NOT quit the application because the // QWindow is still there. quitApplicationTriggered = false; - QTimer::singleShot(2000, this, SLOT(quitApplication())); // This causes the quit. + QTimer::singleShot(2000, this, quitSlot); // This causes the quit. - app.exec(); + QCoreApplication::exec(); QVERIFY(quitApplicationTriggered); // Should be around 20 if closing did not caused the quit } { // QTBUG-31569: If the last widget with Qt::WA_QuitOnClose set is closed, other // widgets that don't have the attribute set should be closed automatically. int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); QVERIFY(app.quitOnLastWindowClosed()); QWidget w1; + w1.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('1')); w1.show(); QWidget w2; + w1.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('2')); w2.setAttribute(Qt::WA_QuitOnClose, false); w2.show(); @@ -778,19 +756,24 @@ void tst_QApplication::quitOnLastWindowClosed() QTimer timer; timer.setInterval(100); timer.start(); - QSignalSpy timerSpy(&timer, SIGNAL(timeout())); + QSignalSpy timerSpy(&timer, &QTimer::timeout); - QTimer::singleShot(100, &w1, SLOT(close())); - app.exec(); + QTimer::singleShot(100, &w1, &QWidget::close); + QCoreApplication::exec(); QVERIFY(timerSpy.count() < 10); } } +static inline bool isVisible(const QWidget *w) +{ + return w->isVisible(); +} + class PromptOnCloseWidget : public QWidget { public: - void closeEvent(QCloseEvent *event) + void closeEvent(QCloseEvent *event) override { QMessageBox *messageBox = new QMessageBox(this); messageBox->setWindowTitle("Unsaved data"); @@ -802,12 +785,12 @@ public: QVERIFY(QTest::qWaitForWindowExposed(messageBox)); // verify that all windows are visible - foreach (QWidget *w, qApp->topLevelWidgets()) - QVERIFY(w->isVisible()); + const auto &topLevels = QApplication::topLevelWidgets(); + QVERIFY(std::all_of(topLevels.cbegin(), topLevels.cend(), ::isVisible)); // flush event queue - qApp->processEvents(); + QCoreApplication::processEvents(); // close all windows - qApp->closeAllWindows(); + QApplication::closeAllWindows(); if (messageBox->standardButton(messageBox->clickedButton()) == QMessageBox::Cancel) event->ignore(); @@ -824,7 +807,7 @@ void tst_QApplication::closeAllWindows() QSKIP("PromptOnCloseWidget does not work on WinRT - QTBUG-68297"); #endif int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); // create some windows new QWidget; @@ -832,39 +815,39 @@ void tst_QApplication::closeAllWindows() new QWidget; // show all windows - foreach (QWidget *w, app.topLevelWidgets()) { + auto topLevels = QApplication::topLevelWidgets(); + for (QWidget *w : qAsConst(topLevels)) { w->show(); QVERIFY(QTest::qWaitForWindowExposed(w)); } // verify that they are visible - foreach (QWidget *w, app.topLevelWidgets()) - QVERIFY(w->isVisible()); + QVERIFY(std::all_of(topLevels.cbegin(), topLevels.cend(), isVisible)); // empty event queue - app.processEvents(); + QCoreApplication::processEvents(); // close all windows - app.closeAllWindows(); + QApplication::closeAllWindows(); // all windows should no longer be visible - foreach (QWidget *w, app.topLevelWidgets()) - QVERIFY(!w->isVisible()); + QVERIFY(std::all_of(topLevels.cbegin(), topLevels.cend(), [] (const QWidget *w) { return !w->isVisible(); })); // add a window that prompts the user when closed PromptOnCloseWidget *promptOnCloseWidget = new PromptOnCloseWidget; // show all windows - foreach (QWidget *w, app.topLevelWidgets()) { + topLevels = QApplication::topLevelWidgets(); + for (QWidget *w : qAsConst(topLevels)) { w->show(); QVERIFY(QTest::qWaitForWindowExposed(w)); } // close the last window to open the prompt (eventloop recurses) promptOnCloseWidget->close(); // all windows should not be visible, except the one that opened the prompt - foreach (QWidget *w, app.topLevelWidgets()) { + for (QWidget *w : qAsConst(topLevels)) { if (w == promptOnCloseWidget) QVERIFY(w->isVisible()); else QVERIFY(!w->isVisible()); } - qDeleteAll(app.topLevelWidgets()); + qDeleteAll(QApplication::topLevelWidgets()); } bool isPathListIncluded(const QStringList &l, const QStringList &r) @@ -888,7 +871,6 @@ bool isPathListIncluded(const QStringList &l, const QStringList &r) } #if QT_CONFIG(library) -#define QT_TST_QAPP_DEBUG void tst_QApplication::libraryPaths() { #ifndef BUILTIN_TESTDATA @@ -904,7 +886,7 @@ void tst_QApplication::libraryPaths() // creating QApplication adds the applicationDirPath to the libraryPath int argc = 1; QApplication app(argc, &argv0); - QString appDirPath = QDir(app.applicationDirPath()).canonicalPath(); + QString appDirPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath(); QStringList actual = QApplication::libraryPaths(); actual.sort(); @@ -921,7 +903,7 @@ void tst_QApplication::libraryPaths() // creating QApplication adds the applicationDirPath and plugin install path to the libraryPath int argc = 1; QApplication app(argc, &argv0); - QString appDirPath = app.applicationDirPath(); + QString appDirPath = QCoreApplication::applicationDirPath(); QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath); QStringList actual = QApplication::libraryPaths(); @@ -946,9 +928,7 @@ void tst_QApplication::libraryPaths() "\nexpected:\n - " + testDir)); } { -#ifdef QT_TST_QAPP_DEBUG - qDebug() << "Initial library path:" << QApplication::libraryPaths(); -#endif + qCDebug(lcTests) << "Initial library path:" << QApplication::libraryPaths(); int count = QApplication::libraryPaths().count(); #if 0 @@ -957,10 +937,8 @@ void tst_QApplication::libraryPaths() #endif QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath); QApplication::addLibraryPath(installPathPlugins); -#ifdef QT_TST_QAPP_DEBUG - qDebug() << "installPathPlugins" << installPathPlugins; - qDebug() << "After adding plugins path:" << QApplication::libraryPaths(); -#endif + qCDebug(lcTests) << "installPathPlugins" << installPathPlugins; + qCDebug(lcTests) << "After adding plugins path:" << QApplication::libraryPaths(); QCOMPARE(QApplication::libraryPaths().count(), count); QApplication::addLibraryPath(testDir); QCOMPARE(QApplication::libraryPaths().count(), count + 1); @@ -968,8 +946,8 @@ void tst_QApplication::libraryPaths() // creating QApplication adds the applicationDirPath to the libraryPath int argc = 1; QApplication app(argc, &argv0); - QString appDirPath = app.applicationDirPath(); - qDebug() << QApplication::libraryPaths(); + QString appDirPath = QCoreApplication::applicationDirPath(); + qCDebug(lcTests) << QApplication::libraryPaths(); // On Windows CE these are identical and might also be the case for other // systems too if (appDirPath != installPathPlugins) @@ -979,36 +957,28 @@ void tst_QApplication::libraryPaths() int argc = 1; QApplication app(argc, &argv0); -#ifdef QT_TST_QAPP_DEBUG - qDebug() << "Initial library path:" << app.libraryPaths(); -#endif - int count = app.libraryPaths().count(); + qCDebug(lcTests) << "Initial library path:" << QCoreApplication::libraryPaths(); + int count = QCoreApplication::libraryPaths().count(); QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath); - app.addLibraryPath(installPathPlugins); -#ifdef QT_TST_QAPP_DEBUG - qDebug() << "installPathPlugins" << installPathPlugins; - qDebug() << "After adding plugins path:" << app.libraryPaths(); -#endif - QCOMPARE(app.libraryPaths().count(), count); - - QString appDirPath = app.applicationDirPath(); - - app.addLibraryPath(appDirPath); - app.addLibraryPath(appDirPath + "/.."); -#ifdef QT_TST_QAPP_DEBUG - qDebug() << "appDirPath" << appDirPath; - qDebug() << "After adding appDirPath && appDirPath + /..:" << app.libraryPaths(); -#endif - QCOMPARE(app.libraryPaths().count(), count + 1); -#ifdef Q_OS_MAC - app.addLibraryPath(appDirPath + "/../MacOS"); + QCoreApplication::addLibraryPath(installPathPlugins); + qCDebug(lcTests) << "installPathPlugins" << installPathPlugins; + qCDebug(lcTests) << "After adding plugins path:" << QCoreApplication::libraryPaths(); + QCOMPARE(QCoreApplication::libraryPaths().count(), count); + + QString appDirPath = QCoreApplication::applicationDirPath(); + + QCoreApplication::addLibraryPath(appDirPath); + QCoreApplication::addLibraryPath(appDirPath + "/.."); + qCDebug(lcTests) << "appDirPath" << appDirPath; + qCDebug(lcTests) << "After adding appDirPath && appDirPath + /..:" << QCoreApplication::libraryPaths(); + QCOMPARE(QCoreApplication::libraryPaths().count(), count + 1); +#ifdef Q_OS_MACOS + QCoreApplication::addLibraryPath(appDirPath + "/../MacOS"); #else - app.addLibraryPath(appDirPath + "/tmp/.."); -#endif -#ifdef QT_TST_QAPP_DEBUG - qDebug() << "After adding appDirPath + /tmp/..:" << app.libraryPaths(); + QCoreApplication::addLibraryPath(appDirPath + "/tmp/.."); #endif - QCOMPARE(app.libraryPaths().count(), count + 1); + qCDebug(lcTests) << "After adding appDirPath + /tmp/..:" << QCoreApplication::libraryPaths(); + QCOMPARE(QCoreApplication::libraryPaths().count(), count + 1); } } @@ -1017,14 +987,14 @@ void tst_QApplication::libraryPaths_qt_plugin_path() int argc = 1; QApplication app(argc, &argv0); - QString appDirPath = app.applicationDirPath(); + QString appDirPath = QCoreApplication::applicationDirPath(); // Our hook into libraryPaths() initialization: Set the QT_PLUGIN_PATH environment variable QString installPathPluginsDeCanon = appDirPath + QString::fromLatin1("/tmp/.."); QByteArray ascii = QFile::encodeName(installPathPluginsDeCanon); qputenv("QT_PLUGIN_PATH", ascii); - QVERIFY(!app.libraryPaths().contains(appDirPath + QString::fromLatin1("/tmp/.."))); + QVERIFY(!QCoreApplication::libraryPaths().contains(appDirPath + QString::fromLatin1("/tmp/.."))); } void tst_QApplication::libraryPaths_qt_plugin_path_2() @@ -1051,14 +1021,14 @@ void tst_QApplication::libraryPaths_qt_plugin_path_2() QStringList expected = QStringList() << QLibraryInfo::location(QLibraryInfo::PluginsPath) - << QDir(app.applicationDirPath()).canonicalPath() + << QDir(QCoreApplication::applicationDirPath()).canonicalPath() << QDir(QDir::fromNativeSeparators(QString::fromLatin1(validPath))).canonicalPath(); #ifdef Q_OS_WINRT QEXPECT_FAIL("", "On WinRT PluginsPath is outside of sandbox. QTBUG-68297", Abort); #endif - QVERIFY2(isPathListIncluded(app.libraryPaths(), expected), - qPrintable("actual:\n - " + app.libraryPaths().join("\n - ") + + QVERIFY2(isPathListIncluded(QCoreApplication::libraryPaths(), expected), + qPrintable("actual:\n - " + QCoreApplication::libraryPaths().join("\n - ") + "\nexpected:\n - " + expected.join("\n - "))); } @@ -1075,8 +1045,8 @@ void tst_QApplication::libraryPaths_qt_plugin_path_2() QStringList expected = QStringList() << QLibraryInfo::location(QLibraryInfo::PluginsPath) - << app.applicationDirPath(); - QVERIFY(isPathListIncluded(app.libraryPaths(), expected)); + << QCoreApplication::applicationDirPath(); + QVERIFY(isPathListIncluded(QCoreApplication::libraryPaths(), expected)); qputenv("QT_PLUGIN_PATH", QByteArray()); } @@ -1088,7 +1058,7 @@ class SendPostedEventsTester : public QObject Q_OBJECT public: QList<int> eventSpy; - bool event(QEvent *e); + bool event(QEvent *e) override; private slots: void doTest(); }; @@ -1109,7 +1079,7 @@ void SendPostedEventsTester::doTest() QEventLoop eventLoop; QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection); eventLoop.exec(); - QVERIFY(p != 0); + QVERIFY(p != nullptr); QCOMPARE(eventSpy.count(), 2); QCOMPARE(eventSpy.at(0), int(QEvent::MetaCall)); @@ -1120,12 +1090,12 @@ void SendPostedEventsTester::doTest() void tst_QApplication::sendPostedEvents() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); SendPostedEventsTester *tester = new SendPostedEventsTester; QMetaObject::invokeMethod(tester, "doTest", Qt::QueuedConnection); QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection); QPointer<SendPostedEventsTester> p = tester; - (void) app.exec(); + (void) QCoreApplication::exec(); QVERIFY(p.isNull()); } @@ -1133,7 +1103,7 @@ void tst_QApplication::thread() { QThread *currentThread = QThread::currentThread(); // no app, but still have a valid thread - QVERIFY(currentThread != 0); + QVERIFY(currentThread != nullptr); // the thread should be running and not finished QVERIFY(currentThread->isRunning()); @@ -1149,10 +1119,10 @@ void tst_QApplication::thread() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); // current thread still valid - QVERIFY(QThread::currentThread() != 0); + QVERIFY(QThread::currentThread() != nullptr); // thread should be the same as before QCOMPARE(QThread::currentThread(), currentThread); @@ -1167,7 +1137,7 @@ void tst_QApplication::thread() } // app dead, current thread still valid - QVERIFY(QThread::currentThread() != 0); + QVERIFY(QThread::currentThread() != nullptr); QCOMPARE(QThread::currentThread(), currentThread); // the thread should still be running and not finished @@ -1182,10 +1152,10 @@ void tst_QApplication::thread() // before { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); // current thread still valid - QVERIFY(QThread::currentThread() != 0); + QVERIFY(QThread::currentThread() != nullptr); // thread should be the same as before QCOMPARE(QThread::currentThread(), currentThread); @@ -1204,7 +1174,7 @@ void tst_QApplication::thread() } // app dead, current thread still valid - QVERIFY(QThread::currentThread() != 0); + QVERIFY(QThread::currentThread() != nullptr); QCOMPARE(QThread::currentThread(), currentThread); // the thread should still be running and not finished @@ -1220,10 +1190,10 @@ class DeleteLaterWidget : public QWidget { Q_OBJECT public: - DeleteLaterWidget(QApplication *_app, QWidget *parent = 0) - : QWidget(parent) { app = _app; child_deleted = false; } + explicit DeleteLaterWidget(QApplication *_app, QWidget *parent = nullptr) + : QWidget(parent), app(_app) {} - bool child_deleted; + bool child_deleted = false; QApplication *app; public slots: @@ -1238,22 +1208,22 @@ void DeleteLaterWidget::runTest() QObject *stillAlive = this->findChild<QObject*>("deleteLater"); QWidget *w = new QWidget(this); - connect(w, SIGNAL(destroyed()), this, SLOT(childDeleted())); + connect(w, &QObject::destroyed, this, &DeleteLaterWidget::childDeleted); w->deleteLater(); QVERIFY(!child_deleted); QDialog dlg; - QTimer::singleShot(500, &dlg, SLOT(reject())); + QTimer::singleShot(500, &dlg, &QDialog::reject); dlg.exec(); QVERIFY(!child_deleted); - app->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!child_deleted); - QTimer::singleShot(500, this, SLOT(checkDeleteLater())); + QTimer::singleShot(500, this, &DeleteLaterWidget::checkDeleteLater); - app->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!stillAlive); // verify at the end to make test terminate } @@ -1271,11 +1241,11 @@ void tst_QApplication::testDeleteLater() QSKIP("This test fails and then hangs on OS X, see QTBUG-24318"); #endif int argc = 0; - QApplication app(argc, 0); - connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); + QApplication app(argc, nullptr); + connect(&app, &QApplication::lastWindowClosed, &app, &QCoreApplication::quit); DeleteLaterWidget *wgt = new DeleteLaterWidget(&app); - QTimer::singleShot(500, wgt, SLOT(runTest())); + QTimer::singleShot(500, wgt, &DeleteLaterWidget::runTest); QObject *object = new QObject(wgt); object->setObjectName("deleteLater"); @@ -1284,7 +1254,7 @@ void tst_QApplication::testDeleteLater() QObject *stillAlive = wgt->findChild<QObject*>("deleteLater"); QVERIFY(stillAlive); - app.exec(); + QCoreApplication::exec(); delete wgt; @@ -1305,7 +1275,7 @@ public slots: event loop */ QMetaObject::invokeMethod(this, "deleteLater", Qt::QueuedConnection); - QTimer::singleShot(1000, &eventLoop, SLOT(quit())); + QTimer::singleShot(1000, &eventLoop, &QEventLoop::quit); eventLoop.exec(); QVERIFY(p); } @@ -1329,7 +1299,7 @@ public slots: } void sendPostedEventsWithDeferredDelete() { - QApplication::sendPostedEvents(0, QEvent::DeferredDelete); + QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); } void deleteLaterAndProcessEvents() @@ -1358,7 +1328,7 @@ public slots: QVERIFY(p); // however, it *will* work with this magic incantation - QApplication::sendPostedEvents(0, QEvent::DeferredDelete); + QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); QVERIFY(!p); } }; @@ -1376,16 +1346,16 @@ void tst_QApplication::testDeleteLaterProcessEvents() delete object; { - QApplication app(argc, 0); + QApplication app(argc, nullptr); // If you call processEvents() with an event dispatcher present, but // outside any event loops, deferred deletes are not processed unless // sendPostedEvents(0, DeferredDelete) is called. object = new QObject; p = object; object->deleteLater(); - app.processEvents(); + QCoreApplication::processEvents(); QVERIFY(p); - QApplication::sendPostedEvents(0, QEvent::DeferredDelete); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); QVERIFY(!p); // If you call deleteLater() on an object when there is no parent @@ -1395,7 +1365,7 @@ void tst_QApplication::testDeleteLaterProcessEvents() p = object; object->deleteLater(); QEventLoop loop; - QTimer::singleShot(1000, &loop, SLOT(quit())); + QTimer::singleShot(1000, &loop, &QEventLoop::quit); loop.exec(); QVERIFY(!p); } @@ -1403,12 +1373,12 @@ void tst_QApplication::testDeleteLaterProcessEvents() // When an object is in an event loop, then calls deleteLater() and enters // an event loop recursively, it should not die until the parent event // loop continues. - QApplication app(argc, 0); + QApplication app(argc, nullptr); QEventLoop loop; EventLoopNester *nester = new EventLoopNester; p = nester; - QTimer::singleShot(3000, &loop, SLOT(quit())); - QTimer::singleShot(0, nester, SLOT(deleteLaterAndEnterLoop())); + QTimer::singleShot(3000, &loop, &QEventLoop::quit); + QTimer::singleShot(0, nester, &EventLoopNester::deleteLaterAndEnterLoop); loop.exec(); QVERIFY(!p); @@ -1418,12 +1388,12 @@ void tst_QApplication::testDeleteLaterProcessEvents() // When the event loop that calls deleteLater() is exited // immediately, the object should die when returning to the // parent event loop - QApplication app(argc, 0); + QApplication app(argc, nullptr); QEventLoop loop; EventLoopNester *nester = new EventLoopNester; p = nester; - QTimer::singleShot(3000, &loop, SLOT(quit())); - QTimer::singleShot(0, nester, SLOT(deleteLaterAndExitLoop())); + QTimer::singleShot(3000, &loop, &QEventLoop::quit); + QTimer::singleShot(0, nester, &EventLoopNester::deleteLaterAndExitLoop); loop.exec(); QVERIFY(!p); @@ -1433,12 +1403,12 @@ void tst_QApplication::testDeleteLaterProcessEvents() // when the event loop that calls deleteLater() also calls // processEvents() immediately afterwards, the object should // not die until the parent loop continues - QApplication app(argc, 0); + QApplication app(argc, nullptr); QEventLoop loop; EventLoopNester *nester = new EventLoopNester(); p = nester; - QTimer::singleShot(3000, &loop, SLOT(quit())); - QTimer::singleShot(0, nester, SLOT(deleteLaterAndProcessEvents())); + QTimer::singleShot(3000, &loop, &QEventLoop::quit); + QTimer::singleShot(0, nester, &EventLoopNester::deleteLaterAndProcessEvents); loop.exec(); QVERIFY(!p); @@ -1464,7 +1434,7 @@ void tst_QApplication::desktopSettingsAware() void tst_QApplication::setActiveWindow() { int argc = 0; - QApplication MyApp(argc, 0); + QApplication MyApp(argc, nullptr); QWidget* w = new QWidget; QVBoxLayout* layout = new QVBoxLayout(w); @@ -1476,7 +1446,7 @@ void tst_QApplication::setActiveWindow() layout->addWidget(pb2); pb2->setFocus(); - pb2->setParent(0); + pb2->setParent(nullptr); delete pb2; w->show(); @@ -1490,13 +1460,14 @@ void tst_QApplication::setActiveWindow() void tst_QApplication::focusChanged() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); - QSignalSpy spy(&app, SIGNAL(focusChanged(QWidget*,QWidget*))); - QWidget *now = 0; - QWidget *old = 0; + QSignalSpy spy(&app, QOverload<QWidget*,QWidget*>::of(&QApplication::focusChanged)); + QWidget *now = nullptr; + QWidget *old = nullptr; QWidget parent1; + parent1.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('1')); QHBoxLayout hbox1(&parent1); QLabel lb1(&parent1); QLineEdit le1(&parent1); @@ -1547,6 +1518,7 @@ void tst_QApplication::focusChanged() spy.clear(); QWidget parent2; + parent2.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char('1')); QHBoxLayout hbox2(&parent2); QLabel lb2(&parent2); QLineEdit le2(&parent2); @@ -1565,9 +1537,9 @@ void tst_QApplication::focusChanged() QVERIFY(!old); spy.clear(); - QTestKeyEvent tab(QTest::Press, Qt::Key_Tab, 0, 0); - QTestKeyEvent backtab(QTest::Press, Qt::Key_Backtab, 0, 0); - QTestMouseEvent click(QTest::MouseClick, Qt::LeftButton, 0, QPoint(5, 5), 0); + QTestKeyEvent tab(QTest::Press, Qt::Key_Tab, Qt::KeyboardModifiers(), 0); + QTestKeyEvent backtab(QTest::Press, Qt::Key_Backtab, Qt::KeyboardModifiers(), 0); + QTestMouseEvent click(QTest::MouseClick, Qt::LeftButton, Qt::KeyboardModifiers(), QPoint(5, 5), 0); bool tabAllControls = true; #ifdef Q_OS_MAC @@ -1683,16 +1655,18 @@ void tst_QApplication::focusChanged() class LineEdit : public QLineEdit { public: - LineEdit(QWidget *parent = 0) : QLineEdit(parent) { } + using QLineEdit::QLineEdit; protected: - void focusOutEvent(QFocusEvent *e) { + void focusOutEvent(QFocusEvent *e) override + { QLineEdit::focusOutEvent(e); if (objectName() == "le1") setStyleSheet(""); } - void focusInEvent(QFocusEvent *e) { + void focusInEvent(QFocusEvent *e) override + { QLineEdit::focusInEvent(e); if (objectName() == "le2") setStyleSheet(""); @@ -1707,6 +1681,7 @@ void tst_QApplication::focusOut() // Tests the case where the style pointer changes when on focus in/out // (the above is the case when the stylesheet changes) QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QLineEdit *le1 = new LineEdit(&w); le1->setObjectName("le1"); le1->setStyleSheet("background: #fee"); @@ -1730,6 +1705,7 @@ void tst_QApplication::focusMouseClick() QApplication app(argc, &argv0); QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setFocusPolicy(Qt::StrongFocus); QWidget w2(&w); w2.setFocusPolicy(Qt::TabFocus); @@ -1772,7 +1748,7 @@ void tst_QApplication::execAfterExit() QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection); // this should be ignored, as exec() will reset the exitCode QApplication::exit(1); - int exitCode = app.exec(); + int exitCode = QCoreApplication::exec(); QCOMPARE(exitCode, 0); // the quitNow flag should have been reset, so we can spin an @@ -1799,15 +1775,15 @@ void tst_QApplication::style() { QApplication app(argc, &argv0); - QPointer<QStyle> style = app.style(); - app.setStyle(QStyleFactory::create(QLatin1String("Windows"))); + QPointer<QStyle> style = QApplication::style(); + QApplication::setStyle(QStyleFactory::create(QLatin1String("Windows"))); QVERIFY(style.isNull()); } QApplication app(argc, &argv0); // qApp style can never be 0 - QVERIFY(QApplication::style() != 0); + QVERIFY(QApplication::style() != nullptr); } void tst_QApplication::allWidgets() @@ -1815,11 +1791,9 @@ void tst_QApplication::allWidgets() int argc = 1; QApplication app(argc, &argv0); QWidget *w = new QWidget; - QVERIFY(app.allWidgets().contains(w)); // uncreate widget test - QVERIFY(app.allWidgets().contains(w)); // created widget test + QVERIFY(QApplication::allWidgets().contains(w)); // uncreate widget test delete w; - w = 0; - QVERIFY(!app.allWidgets().contains(w)); // removal test + QVERIFY(!QApplication::allWidgets().contains(w)); // removal test } void tst_QApplication::topLevelWidgets() @@ -1829,16 +1803,15 @@ void tst_QApplication::topLevelWidgets() QWidget *w = new QWidget; w->show(); #ifndef QT_NO_CLIPBOARD - QClipboard *clipboard = QApplication::clipboard(); - QString originalText = clipboard->text(); - clipboard->setText(QString("newText")); + QClipboard *clipboard = QGuiApplication::clipboard(); + clipboard->setText(QLatin1String("newText")); #endif - app.processEvents(); + QCoreApplication::processEvents(); QVERIFY(QApplication::topLevelWidgets().contains(w)); QCOMPARE(QApplication::topLevelWidgets().count(), 1); delete w; - w = 0; - app.processEvents(); + w = nullptr; + QCoreApplication::processEvents(); QCOMPARE(QApplication::topLevelWidgets().count(), 0); } @@ -1858,7 +1831,7 @@ void tst_QApplication::setAttribute() w = new QWidget; QVERIFY(w->testAttribute(Qt::WA_WState_Created)); QWidget *w2 = new QWidget(w); - w2->setParent(0); + w2->setParent(nullptr); QVERIFY(w2->testAttribute(Qt::WA_WState_Created)); delete w; delete w2; @@ -1875,10 +1848,10 @@ class TouchEventPropagationTestWidget : public QWidget Q_OBJECT public: - bool seenTouchEvent, acceptTouchEvent, seenMouseEvent, acceptMouseEvent; + bool seenTouchEvent = false, acceptTouchEvent = false, seenMouseEvent = false, acceptMouseEvent = false; + - TouchEventPropagationTestWidget(QWidget *parent = 0) - : QWidget(parent), seenTouchEvent(false), acceptTouchEvent(false), seenMouseEvent(false), acceptMouseEvent(false) + explicit TouchEventPropagationTestWidget(QWidget *parent = nullptr) : QWidget(parent) { setAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents); } @@ -1888,7 +1861,7 @@ public: seenTouchEvent = acceptTouchEvent = seenMouseEvent = acceptMouseEvent = false; } - bool event(QEvent *event) + bool event(QEvent *event) override { switch (event->type()) { case QEvent::MouseButtonPress: @@ -1932,11 +1905,13 @@ void tst_QApplication::touchEventPropagation() { // touch event behavior on a window TouchEventPropagationTestWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); window.setObjectName("1. window"); window.show(); // Must have an explicitly specified QWindow for handleTouchEvent, // passing 0 would result in using topLevelAt() which is not ok in this case // as the screen position in the point is bogus. + auto handle = window.windowHandle(); QVERIFY(QTest::qWaitForWindowExposed(&window)); // QPA always takes screen positions and since we map the TouchPoint back to QPA's structure first, // we must ensure there is a screen position in the TouchPoint that maps to a local 0, 0. @@ -1945,42 +1920,42 @@ void tst_QApplication::touchEventPropagation() pressedTouchPoints[0].setScreenPos(deviceGlobalPos); releasedTouchPoints[0].setScreenPos(deviceGlobalPos); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(!window.seenTouchEvent); QVERIFY(window.seenMouseEvent); // QApplication may transform ignored touch events in mouse events window.reset(); window.setAttribute(Qt::WA_AcceptTouchEvents); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(window.seenTouchEvent); QVERIFY(window.seenMouseEvent); window.reset(); window.acceptTouchEvent = true; - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(window.seenTouchEvent); QVERIFY(!window.seenMouseEvent); @@ -1989,26 +1964,28 @@ void tst_QApplication::touchEventPropagation() { // touch event behavior on a window with a child widget TouchEventPropagationTestWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); window.setObjectName("2. window"); TouchEventPropagationTestWidget widget(&window); widget.resize(200, 200); widget.setObjectName("2. widget"); window.show(); + auto handle = window.windowHandle(); QVERIFY(QTest::qWaitForWindowExposed(&window)); const QPoint deviceGlobalPos = QHighDpi::toNativePixels(window.mapToGlobal(QPoint(50, 150)), window.windowHandle()->screen()); pressedTouchPoints[0].setScreenPos(deviceGlobalPos); releasedTouchPoints[0].setScreenPos(deviceGlobalPos); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QTRY_VERIFY(widget.seenMouseEvent); QVERIFY(!widget.seenTouchEvent); QVERIFY(!window.seenTouchEvent); @@ -2017,14 +1994,14 @@ void tst_QApplication::touchEventPropagation() window.reset(); widget.reset(); widget.setAttribute(Qt::WA_AcceptTouchEvents); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(widget.seenTouchEvent); QVERIFY(widget.seenMouseEvent); @@ -2034,14 +2011,14 @@ void tst_QApplication::touchEventPropagation() window.reset(); widget.reset(); widget.acceptMouseEvent = true; - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(widget.seenTouchEvent); QVERIFY(widget.seenMouseEvent); @@ -2051,14 +2028,14 @@ void tst_QApplication::touchEventPropagation() window.reset(); widget.reset(); widget.acceptTouchEvent = true; - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(widget.seenTouchEvent); QVERIFY(!widget.seenMouseEvent); @@ -2069,14 +2046,14 @@ void tst_QApplication::touchEventPropagation() widget.reset(); widget.setAttribute(Qt::WA_AcceptTouchEvents, false); window.setAttribute(Qt::WA_AcceptTouchEvents); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(!widget.seenTouchEvent); QVERIFY(widget.seenMouseEvent); @@ -2086,14 +2063,14 @@ void tst_QApplication::touchEventPropagation() window.reset(); widget.reset(); window.acceptTouchEvent = true; - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(!widget.seenTouchEvent); QVERIFY(!widget.seenMouseEvent); @@ -2104,14 +2081,14 @@ void tst_QApplication::touchEventPropagation() widget.reset(); widget.acceptMouseEvent = true; // doesn't matter, touch events are propagated first window.acceptTouchEvent = true; - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(pressedTouchPoints)); - QWindowSystemInterface::handleTouchEvent(window.windowHandle(), + QWindowSystemInterfacePrivate::toNativeTouchPoints(pressedTouchPoints, handle)); + QWindowSystemInterface::handleTouchEvent(handle, 0, device, - touchPointList(releasedTouchPoints)); + QWindowSystemInterfacePrivate::toNativeTouchPoints(releasedTouchPoints, handle)); QCoreApplication::processEvents(); QVERIFY(!widget.seenTouchEvent); QVERIFY(!widget.seenMouseEvent); @@ -2139,37 +2116,33 @@ class NoQuitOnHideWidget : public QWidget { Q_OBJECT public: - explicit NoQuitOnHideWidget(QWidget *parent = 0) + explicit NoQuitOnHideWidget(QWidget *parent = nullptr) : QWidget(parent) { - QTimer::singleShot(0, this, SLOT(hide())); - QTimer::singleShot(500, this, SLOT(exitApp())); - } - -private slots: - void exitApp() { - qApp->exit(1); + QTimer::singleShot(0, this, &QWidget::hide); + QTimer::singleShot(500, this, [] () { QCoreApplication::exit(1); }); } }; void tst_QApplication::noQuitOnHide() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); NoQuitOnHideWidget window1; + window1.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window1.show(); - QCOMPARE(app.exec(), 1); + QCOMPARE(QCoreApplication::exec(), 1); } class ShowCloseShowWidget : public QWidget { Q_OBJECT public: - ShowCloseShowWidget(bool showAgain, QWidget *parent = 0) - : QWidget(parent), showAgain(showAgain) + explicit ShowCloseShowWidget(bool showAgain, QWidget *parent = nullptr) + : QWidget(parent), showAgain(showAgain) { - QTimer::singleShot(0, this, SLOT(doClose())); - QTimer::singleShot(500, this, SLOT(exitApp())); + QTimer::singleShot(0, this, &ShowCloseShowWidget::doClose); + QTimer::singleShot(500, this, [] () { QCoreApplication::exit(1); }); } private slots: @@ -2179,25 +2152,23 @@ private slots: show(); } - void exitApp() { - qApp->exit(1); - } - private: - bool showAgain; + const bool showAgain; }; void tst_QApplication::abortQuitOnShow() { int argc = 0; - QApplication app(argc, 0); + QApplication app(argc, nullptr); ShowCloseShowWidget window1(false); + window1.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window1.show(); - QCOMPARE(app.exec(), 0); + QCOMPARE(QCoreApplication::exec(), 0); ShowCloseShowWidget window2(true); + window2.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window2.show(); - QCOMPARE(app.exec(), 1); + QCOMPARE(QCoreApplication::exec(), 1); } // Test that static functions do not crash if there is no application instance. @@ -2233,7 +2204,7 @@ void tst_QApplication::settableStyleHints() int argc = 0; QScopedPointer<QApplication> app; if (appInstance) - app.reset(new QApplication(argc, 0)); + app.reset(new QApplication(argc, nullptr)); QApplication::setCursorFlashTime(437); QCOMPARE(QApplication::cursorFlashTime(), 437); @@ -2299,12 +2270,6 @@ void tst_QApplication::globalStaticObjectDestruction() #endif } -void tst_QApplication::quitApplication() -{ - quitApplicationTriggered = true; - qApp->quit(); -} - //QTEST_APPLESS_MAIN(tst_QApplication) int main(int argc, char *argv[]) { diff --git a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp index 89da56cd0c..7203e7b170 100644 --- a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp +++ b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp @@ -83,14 +83,16 @@ using namespace QTestPrivate; #include <qpa/qplatformnativeinterface.h> #include <qpa/qplatformintegration.h> +#include <algorithm> + static HWND winHandleOf(const QWidget *w) { static QPlatformNativeInterface *nativeInterface - = QGuiApplicationPrivate::instance()->platformIntegration()->nativeInterface(); + = QGuiApplicationPrivate::platformIntegration()->nativeInterface(); if (void *handle = nativeInterface->nativeResourceForWindow("handle", w->window()->windowHandle())) return reinterpret_cast<HWND>(handle); qWarning() << "Cannot obtain native handle for " << w; - return 0; + return nullptr; } # define Q_CHECK_PAINTEVENTS \ @@ -434,9 +436,9 @@ void tst_QWidget::getSetCheck() QScopedPointer<QStyle> var1(QStyleFactory::create(QLatin1String("Windows"))); obj1.setStyle(var1.data()); QCOMPARE(static_cast<QStyle *>(var1.data()), obj1.style()); - obj1.setStyle((QStyle *)0); + obj1.setStyle(nullptr); QVERIFY(var1.data() != obj1.style()); - QVERIFY(0 != obj1.style()); // style can never be 0 for a widget + QVERIFY(obj1.style() != nullptr); // style can never be 0 for a widget // int QWidget::minimumWidth() // void QWidget::setMinimumWidth(int) @@ -512,7 +514,7 @@ void tst_QWidget::getSetCheck() // void QWidget::setWindowOpacity(qreal) obj1.setWindowOpacity(0.0); QCOMPARE(0.0, obj1.windowOpacity()); - obj1.setWindowOpacity(1.1f); + obj1.setWindowOpacity(1.1); QCOMPARE(1.0, obj1.windowOpacity()); // 1.0 is the fullest opacity possible // QWidget * QWidget::focusProxy() @@ -521,16 +523,16 @@ void tst_QWidget::getSetCheck() QScopedPointer<QWidget> var9(new QWidget()); obj1.setFocusProxy(var9.data()); QCOMPARE(var9.data(), obj1.focusProxy()); - obj1.setFocusProxy((QWidget *)0); - QCOMPARE((QWidget *)0, obj1.focusProxy()); + obj1.setFocusProxy(nullptr); + QCOMPARE(nullptr, obj1.focusProxy()); } // const QRect & QWidget::geometry() // void QWidget::setGeometry(const QRect &) - qApp->processEvents(); + QCoreApplication::processEvents(); QRect var10(10, 10, 100, 100); obj1.setGeometry(var10); - qApp->processEvents(); + QCoreApplication::processEvents(); qDebug() << obj1.geometry(); QCOMPARE(var10, obj1.geometry()); obj1.setGeometry(QRect(0,0,0,0)); @@ -542,10 +544,10 @@ void tst_QWidget::getSetCheck() QBoxLayout *var11 = new QBoxLayout(QBoxLayout::LeftToRight); obj1.setLayout(var11); QCOMPARE(static_cast<QLayout *>(var11), obj1.layout()); - obj1.setLayout((QLayout *)0); + obj1.setLayout(nullptr); QCOMPARE(static_cast<QLayout *>(var11), obj1.layout()); // You cannot set a 0-pointer layout, that keeps the current delete var11; // This will remove the layout from the widget - QCOMPARE((QLayout *)0, obj1.layout()); + QCOMPARE(nullptr, obj1.layout()); // bool QWidget::acceptDrops() // void QWidget::setAcceptDrops(bool) @@ -565,7 +567,7 @@ void tst_QWidget::getSetCheck() #if defined (Q_OS_WIN) && !defined(Q_OS_WINRT) obj1.setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); const HWND handle = reinterpret_cast<HWND>(obj1.winId()); // explicitly create window handle - QVERIFY(GetWindowLong(handle, GWL_STYLE) & WS_POPUP); + QVERIFY(GetWindowLong(handle, GWL_STYLE) & LONG(WS_POPUP)); #endif } @@ -580,12 +582,12 @@ tst_QWidget::tst_QWidget() QFont font; font.setBold(true); font.setPointSize(42); - qApp->setFont(font, "QPropagationTestWidget"); + QApplication::setFont(font, "QPropagationTestWidget"); QPalette palette; palette.setColor(QPalette::ToolTipBase, QColor(12, 13, 14)); palette.setColor(QPalette::Text, QColor(21, 22, 23)); - qApp->setPalette(palette, "QPropagationTestWidget"); + QApplication::setPalette(palette, "QPropagationTestWidget"); } tst_QWidget::~tst_QWidget() @@ -594,16 +596,6 @@ tst_QWidget::~tst_QWidget() setWindowsAnimationsEnabled(m_windowsAnimationsEnabled); } -class BezierViewer : public QWidget { -public: - explicit BezierViewer(QWidget* parent = 0); - void paintEvent( QPaintEvent* ); - void setPoints( const QPolygonF& poly ); -private: - QPolygonF points; - -}; - void tst_QWidget::initTestCase() { // Size of reference widget, 200 for < 2000, scale up for larger screens @@ -730,9 +722,7 @@ class QPropagationTestWidget : public QWidget { Q_OBJECT public: - QPropagationTestWidget(QWidget *parent = 0) - : QWidget(parent) - { } + using QWidget::QWidget; }; void tst_QWidget::fontPropagation2() @@ -741,7 +731,7 @@ void tst_QWidget::fontPropagation2() // QFont font; // font.setBold(true); // font.setPointSize(42); - // qApp->setFont(font, "QPropagationTestWidget"); + // QApplication::setFont(font, "QPropagationTestWidget"); QScopedPointer<QWidget> root(new QWidget); root->setObjectName(QLatin1String("fontPropagation2")); @@ -798,7 +788,7 @@ void tst_QWidget::fontPropagation2() QFont italicSizeFont; italicSizeFont.setItalic(true); italicSizeFont.setPointSize(33); - qApp->setFont(italicSizeFont, "QPropagationTestWidget"); + QApplication::setFont(italicSizeFont, "QPropagationTestWidget"); // Check that this propagates correctly. QCOMPARE(root->font(), QApplication::font()); @@ -951,7 +941,7 @@ void tst_QWidget::palettePropagation2() // should still be ignored. The previous ToolTipBase setting is gone. QPalette buttonPalette; buttonPalette.setColor(QPalette::ToolTipText, sysPalButton); - qApp->setPalette(buttonPalette, "QPropagationTestWidget"); + QApplication::setPalette(buttonPalette, "QPropagationTestWidget"); // Check that the above settings propagate correctly. QCOMPARE(root->palette(), appPal); @@ -1138,7 +1128,7 @@ void tst_QWidget::isEnabledTo() QScopedPointer<QMainWindow> childDialog(new QMainWindow(&testWidget)); testWidget.setEnabled(false); QVERIFY(!childDialog->isEnabled()); - QVERIFY(childDialog->isEnabledTo(0)); + QVERIFY(childDialog->isEnabledTo(nullptr)); } void tst_QWidget::visible() @@ -1583,8 +1573,8 @@ void tst_QWidget::focusChainOnReparent() QWidget *expectedOriginalChain[8] = {&window, child1, child2, child3, child21, child22, child4, &window}; QWidget *w = &window; - for (int i = 0; i <8; ++i) { - QCOMPARE(w, expectedOriginalChain[i]); + for (auto expectedOriginal : expectedOriginalChain) { + QCOMPARE(w, expectedOriginal); w = w->nextInFocusChain(); } for (int i = 7; i >= 0; --i) { @@ -1597,8 +1587,8 @@ void tst_QWidget::focusChainOnReparent() QWidget *expectedNewChain[5] = {&window2, child2, child21, child22, &window2}; w = &window2; - for (int i = 0; i <5; ++i) { - QCOMPARE(w, expectedNewChain[i]); + for (auto expectedNew : expectedNewChain) { + QCOMPARE(w, expectedNew); w = w->nextInFocusChain(); } for (int i = 4; i >= 0; --i) { @@ -1608,8 +1598,8 @@ void tst_QWidget::focusChainOnReparent() QWidget *expectedOldChain[5] = {&window, child1, child3, child4, &window}; w = &window; - for (int i = 0; i <5; ++i) { - QCOMPARE(w, expectedOldChain[i]); + for (auto expectedOld : expectedOldChain) { + QCOMPARE(w, expectedOld); w = w->nextInFocusChain(); } for (int i = 4; i >= 0; --i) { @@ -1633,7 +1623,7 @@ void tst_QWidget::focusChainOnHide() QWidget::setTabOrder(child, parent.data()); parent->show(); - qApp->setActiveWindow(parent->window()); + QApplication::setActiveWindow(parent->window()); child->activateWindow(); child->setFocus(); @@ -1641,7 +1631,7 @@ void tst_QWidget::focusChainOnHide() child->hide(); QTRY_VERIFY(parent->hasFocus()); - QCOMPARE(parent.data(), qApp->focusWidget()); + QCOMPARE(parent.data(), QApplication::focusWidget()); } class Container : public QWidget @@ -1669,7 +1659,7 @@ public: class Composite : public QFrame { public: - Composite(QWidget* parent = 0, const QString &name = 0) + explicit Composite(QWidget *parent = nullptr, const QString &name = QString()) : QFrame(parent) { setObjectName(name); @@ -1708,9 +1698,10 @@ void tst_QWidget::defaultTabOrder() QLineEdit *lastEdit = new QLineEdit(); container.box->addWidget(lastEdit); + container.setWindowTitle(QLatin1String(QTest::currentTestFunction())); container.show(); container.activateWindow(); - qApp->setActiveWindow(&container); + QApplication::setActiveWindow(&container); QVERIFY(QTest::qWaitForWindowActive(&container)); QTRY_VERIFY(firstEdit->hasFocus()); @@ -1748,6 +1739,7 @@ void tst_QWidget::reverseTabOrder() { const int compositeCount = 2; Container container; + container.setWindowTitle(QLatin1String(QTest::currentTestFunction())); Composite* composite[compositeCount]; QLineEdit *firstEdit = new QLineEdit(); @@ -1767,7 +1759,7 @@ void tst_QWidget::reverseTabOrder() container.show(); container.activateWindow(); - qApp->setActiveWindow(&container); + QApplication::setActiveWindow(&container); QVERIFY(QTest::qWaitForWindowActive(&container)); QTRY_VERIFY(firstEdit->hasFocus()); @@ -1806,6 +1798,7 @@ void tst_QWidget::tabOrderWithProxy() { const int compositeCount = 2; Container container; + container.setWindowTitle(QLatin1String(QTest::currentTestFunction())); Composite* composite[compositeCount]; QLineEdit *firstEdit = new QLineEdit(); @@ -1825,7 +1818,7 @@ void tst_QWidget::tabOrderWithProxy() container.show(); container.activateWindow(); - qApp->setActiveWindow(&container); + QApplication::setActiveWindow(&container); QVERIFY(QTest::qWaitForWindowActive(&container)); QTRY_VERIFY(firstEdit->hasFocus()); @@ -1863,13 +1856,14 @@ void tst_QWidget::tabOrderWithCompoundWidgets() { const int compositeCount = 4; Container container; + container.setWindowTitle(QLatin1String(QTest::currentTestFunction())); Composite *composite[compositeCount]; QLineEdit *firstEdit = new QLineEdit(); container.box->addWidget(firstEdit); for (int i = 0; i < compositeCount; i++) { - composite[i] = new Composite(0, QStringLiteral("Composite: ") + QString::number(i)); + composite[i] = new Composite(nullptr, QStringLiteral("Composite: ") + QString::number(i)); container.box->addWidget(composite[i]); // Let the composite handle focus, and set a child as focus proxy (use the second child, just @@ -1895,7 +1889,7 @@ void tst_QWidget::tabOrderWithCompoundWidgets() container.show(); container.activateWindow(); - qApp->setActiveWindow(&container); + QApplication::setActiveWindow(&container); QVERIFY(QTest::qWaitForWindowActive(&container)); lastEdit->setFocus(); @@ -2308,26 +2302,27 @@ void tst_QWidget::showFullScreen() class ResizeWidget : public QWidget { public: - ResizeWidget(QWidget *p = 0) : QWidget(p) + explicit ResizeWidget(QWidget *p = nullptr) : QWidget(p) { setObjectName(QLatin1String("ResizeWidget")); setWindowTitle(objectName()); - m_resizeEventCount = 0; } protected: - void resizeEvent(QResizeEvent *e){ + void resizeEvent(QResizeEvent *e) override + { QCOMPARE(size(), e->size()); ++m_resizeEventCount; } public: - int m_resizeEventCount; + int m_resizeEventCount = 0; }; void tst_QWidget::resizeEvent() { { QWidget wParent; + wParent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); wParent.resize(200, 200); ResizeWidget wChild(&wParent); wParent.show(); @@ -2345,6 +2340,7 @@ void tst_QWidget::resizeEvent() { ResizeWidget wTopLevel; + wTopLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); wTopLevel.resize(200, 200); wTopLevel.show(); QVERIFY(QTest::qWaitForWindowExposed(&wTopLevel)); @@ -2372,6 +2368,7 @@ void tst_QWidget::showMinimized() } QWidget plain; + plain.setWindowTitle(QLatin1String(QTest::currentTestFunction())); plain.move(100, 100); plain.resize(200, 200); QPoint pos = plain.pos(); @@ -2426,17 +2423,18 @@ void tst_QWidget::showMinimizedKeepsFocus() //here we test that minimizing a widget and restoring it doesn't change the focus inside of it { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget child1(&window), child2(&window); child1.setFocusPolicy(Qt::StrongFocus); child2.setFocusPolicy(Qt::StrongFocus); window.show(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowActive(&window)); child2.setFocus(); QTRY_COMPARE(window.focusWidget(), &child2); - QTRY_COMPARE(qApp->focusWidget(), &child2); + QTRY_COMPARE(QApplication::focusWidget(), &child2); window.showMinimized(); QTRY_VERIFY(window.isMinimized()); @@ -2450,15 +2448,16 @@ void tst_QWidget::showMinimizedKeepsFocus() //testing deletion of the focusWidget { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget *child = new QWidget(&window); child->setFocusPolicy(Qt::StrongFocus); window.show(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowActive(&window)); child->setFocus(); QTRY_COMPARE(window.focusWidget(), child); - QTRY_COMPARE(qApp->focusWidget(), child); + QTRY_COMPARE(QApplication::focusWidget(), child); delete child; QCOMPARE(window.focusWidget(), nullptr); @@ -2468,17 +2467,18 @@ void tst_QWidget::showMinimizedKeepsFocus() //testing reparenting the focus widget { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget *child = new QWidget(&window); child->setFocusPolicy(Qt::StrongFocus); window.show(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowActive(&window)); child->setFocus(); QTRY_COMPARE(window.focusWidget(), child); - QTRY_COMPARE(qApp->focusWidget(), child); + QTRY_COMPARE(QApplication::focusWidget(), child); - child->setParent(0); + child->setParent(nullptr); QScopedPointer<QWidget> childGuard(child); QCOMPARE(window.focusWidget(), nullptr); QCOMPARE(QApplication::focusWidget(), nullptr); @@ -2487,15 +2487,16 @@ void tst_QWidget::showMinimizedKeepsFocus() //testing setEnabled(false) { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget *child = new QWidget(&window); child->setFocusPolicy(Qt::StrongFocus); window.show(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowActive(&window)); child->setFocus(); QTRY_COMPARE(window.focusWidget(), child); - QTRY_COMPARE(qApp->focusWidget(), child); + QTRY_COMPARE(QApplication::focusWidget(), child); child->setEnabled(false); QCOMPARE(window.focusWidget(), nullptr); @@ -2505,17 +2506,18 @@ void tst_QWidget::showMinimizedKeepsFocus() //testing clearFocus { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget *firstchild = new QWidget(&window); firstchild->setFocusPolicy(Qt::StrongFocus); QWidget *child = new QWidget(&window); child->setFocusPolicy(Qt::StrongFocus); window.show(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowActive(&window)); child->setFocus(); QTRY_COMPARE(window.focusWidget(), child); - QTRY_COMPARE(qApp->focusWidget(), child); + QTRY_COMPARE(QApplication::focusWidget(), child); child->clearFocus(); QCOMPARE(window.focusWidget(), nullptr); @@ -2528,7 +2530,7 @@ void tst_QWidget::showMinimizedKeepsFocus() QTRY_COMPARE(QApplication::focusWidget(), nullptr); window.showNormal(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowActive(&window)); #ifdef Q_OS_OSX if (!macHasAccessToWindowsServer()) @@ -2543,7 +2545,7 @@ void tst_QWidget::showMinimizedKeepsFocus() #elif defined(Q_OS_WINRT) QEXPECT_FAIL("", "Winrt fails here - QTBUG-68297", Continue); #endif - QTRY_COMPARE(qApp->focusWidget(), firstchild); + QTRY_COMPARE(QApplication::focusWidget(), firstchild); } } @@ -2555,7 +2557,7 @@ void tst_QWidget::reparent() const QPoint parentPosition = m_availableTopLeft + QPoint(300, 300); parent.setGeometry(QRect(parentPosition, m_testWidgetSize)); - QWidget child(0); + QWidget child; child.setObjectName("child"); child.setGeometry(10, 10, 180, 130); QPalette pal1; @@ -2582,7 +2584,7 @@ void tst_QWidget::reparent() QPoint childPos = parent.mapToGlobal(child.pos()); QPoint tlwPos = childTLW.pos(); - child.setParent(0, child.windowFlags() & ~Qt::WindowType_Mask); + child.setParent(nullptr, child.windowFlags() & ~Qt::WindowType_Mask); child.setGeometry(childPos.x(), childPos.y(), child.width(), child.height()); child.show(); @@ -2649,17 +2651,17 @@ void tst_QWidget::hideWhenFocusWidgetIsChild() QVERIFY(QTest::qWaitForWindowActive(testWidget.data())); QString actualFocusWidget, expectedFocusWidget; - if (!qApp->focusWidget() && m_platform == QStringLiteral("xcb")) + if (!QApplication::focusWidget() && m_platform == QStringLiteral("xcb")) QSKIP("X11: Your window manager is too broken for this test"); - QVERIFY(qApp->focusWidget()); - actualFocusWidget = QString::asprintf("%p %s %s", qApp->focusWidget(), qApp->focusWidget()->objectName().toLatin1().constData(), qApp->focusWidget()->metaObject()->className()); + QVERIFY(QApplication::focusWidget()); + actualFocusWidget = QString::asprintf("%p %s %s", QApplication::focusWidget(), QApplication::focusWidget()->objectName().toLatin1().constData(), QApplication::focusWidget()->metaObject()->className()); expectedFocusWidget = QString::asprintf("%p %s %s", edit, edit->objectName().toLatin1().constData(), edit->metaObject()->className()); QCOMPARE(actualFocusWidget, expectedFocusWidget); parentWidget->hide(); - qApp->processEvents(); - actualFocusWidget = QString::asprintf("%p %s %s", qApp->focusWidget(), qApp->focusWidget()->objectName().toLatin1().constData(), qApp->focusWidget()->metaObject()->className()); + QCoreApplication::processEvents(); + actualFocusWidget = QString::asprintf("%p %s %s", QApplication::focusWidget(), QApplication::focusWidget()->objectName().toLatin1().constData(), QApplication::focusWidget()->metaObject()->className()); expectedFocusWidget = QString::asprintf("%p %s %s", edit2, edit2->objectName().toLatin1().constData(), edit2->metaObject()->className()); QCOMPARE(actualFocusWidget, expectedFocusWidget); } @@ -2776,6 +2778,7 @@ void tst_QWidget::normalGeometry() void tst_QWidget::setGeometry() { QWidget tlw; + tlw.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget child(&tlw); QRect tr(100,100,200,200); @@ -2788,7 +2791,7 @@ void tst_QWidget::setGeometry() QTRY_COMPARE(tlw.geometry().size(), tr.size()); QCOMPARE(child.geometry(), cr); - tlw.setParent(0, Qt::Window|Qt::FramelessWindowHint); + tlw.setParent(nullptr, Qt::Window|Qt::FramelessWindowHint); tr = QRect(0,0,100,100); tr.moveTopLeft(QGuiApplication::primaryScreen()->availableGeometry().topLeft()); tlw.setGeometry(tr); @@ -2836,13 +2839,14 @@ void tst_QWidget::windowOpacity() class UpdateWidget : public QWidget { public: - UpdateWidget(QWidget *parent = 0) : QWidget(parent) { + explicit UpdateWidget(QWidget *parent = nullptr) : QWidget(parent) + { setObjectName(QLatin1String("UpdateWidget")); - setWindowTitle(objectName()); reset(); } - void paintEvent(QPaintEvent *e) { + void paintEvent(QPaintEvent *e) override + { paintedRegion += e->region(); ++numPaintEvents; if (resizeInPaintEvent) { @@ -2851,7 +2855,7 @@ public: } } - bool event(QEvent *event) + bool event(QEvent *event) override { switch (event->type()) { case QEvent::ZOrderChange: @@ -2874,12 +2878,10 @@ public: return QWidget::event(event); } - void reset() { - numPaintEvents = 0; - numZOrderChangeEvents = 0; - numUpdateRequestEvents = 0; - updateOnActivationChangeAndFocusIn = false; - resizeInPaintEvent = false; + void reset() + { + numPaintEvents = numZOrderChangeEvents = numUpdateRequestEvents = 0; + updateOnActivationChangeAndFocusIn = resizeInPaintEvent = false; paintedRegion = QRegion(); } @@ -2896,6 +2898,7 @@ void tst_QWidget::lostUpdatesOnHide() #ifndef Q_OS_OSX UpdateWidget widget; widget.setAttribute(Qt::WA_DontShowOnScreen); + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.show(); widget.hide(); QTest::qWait(50); @@ -2939,12 +2942,11 @@ void tst_QWidget::raise() } #endif - QList<QObject *> list1; - list1 << child1 << child2 << child3 << child4; + QObjectList list1{child1, child2, child3, child4}; QCOMPARE(parentPtr->children(), list1); QCOMPARE(allChildren.count(), list1.count()); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = child == child4 ? 1 : 0; if (expectedPaintEvents == 0) { QCOMPARE(child->numPaintEvents, 0); @@ -2960,7 +2962,7 @@ void tst_QWidget::raise() child2->raise(); QTest::qWait(50); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = child == child2 ? 1 : 0; int expectedZOrderChangeEvents = child == child2 ? 1 : 0; QTRY_COMPARE(child->numPaintEvents, expectedPaintEvents); @@ -2975,6 +2977,7 @@ void tst_QWidget::raise() // Creates a widget on top of all the children and checks that raising one of // the children underneath doesn't trigger a repaint on the covering widget. QWidget topLevel; + topLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget *parent = parentPtr.take(); parent->setParent(&topLevel); topLevel.show(); @@ -2989,7 +2992,7 @@ void tst_QWidget::raise() onTop->reset(); // Reset all the children. - foreach (UpdateWidget *child, allChildren) + for (UpdateWidget *child : qAsConst(allChildren)) child->reset(); for (int i = 0; i < 5; ++i) @@ -2999,11 +3002,10 @@ void tst_QWidget::raise() QCOMPARE(onTop->numPaintEvents, 0); QCOMPARE(onTop->numZOrderChangeEvents, 0); - QList<QObject *> list3; - list3 << child1 << child4 << child2 << child3; + QObjectList list3{child1, child4, child2, child3}; QCOMPARE(parent->children(), list3); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = 0; int expectedZOrderChangeEvents = child == child3 ? 1 : 0; QTRY_COMPARE(child->numPaintEvents, expectedPaintEvents); @@ -3039,12 +3041,11 @@ void tst_QWidget::lower() parent->show(); QVERIFY(QTest::qWaitForWindowExposed(parent.data())); - QList<QObject *> list1; - list1 << child1 << child2 << child3 << child4; + QObjectList list1{child1, child2, child3, child4}; QCOMPARE(parent->children(), list1); QCOMPARE(allChildren.count(), list1.count()); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = child == child4 ? 1 : 0; if (expectedPaintEvents == 0) { QCOMPARE(child->numPaintEvents, 0); @@ -3061,7 +3062,7 @@ void tst_QWidget::lower() QTest::qWait(100); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = child == child3 ? 1 : 0; int expectedZOrderChangeEvents = child == child4 ? 1 : 0; QTRY_COMPARE(child->numZOrderChangeEvents, expectedZOrderChangeEvents); @@ -3104,11 +3105,10 @@ void tst_QWidget::stackUnder() parent->show(); QVERIFY(QTest::qWaitForWindowExposed(parent.data())); - QList<QObject *> list1; - list1 << child1 << child2 << child3 << child4; + QObjectList list1{child1, child2, child3, child4}; QCOMPARE(parent->children(), list1); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = child == child4 ? 1 : 0; #if defined(Q_OS_WIN) || defined(Q_OS_OSX) if (expectedPaintEvents == 1 && child->numPaintEvents == 2) @@ -3123,11 +3123,10 @@ void tst_QWidget::stackUnder() child4->stackUnder(child2); QTest::qWait(10); - QList<QObject *> list2; - list2 << child1 << child4 << child2 << child3; + QObjectList list2{child1, child4, child2, child3}; QCOMPARE(parent->children(), list2); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedPaintEvents = child == child3 ? 1 : 0; int expectedZOrderChangeEvents = child == child4 ? 1 : 0; QTRY_COMPARE(child->numPaintEvents, expectedPaintEvents); @@ -3139,11 +3138,10 @@ void tst_QWidget::stackUnder() child1->stackUnder(child3); QTest::qWait(10); - QList<QObject *> list3; - list3 << child4 << child2 << child1 << child3; + QObjectList list3{child4, child2, child1, child3}; QCOMPARE(parent->children(), list3); - foreach (UpdateWidget *child, allChildren) { + for (UpdateWidget *child : qAsConst(allChildren)) { int expectedZOrderChangeEvents = child == child1 ? 1 : 0; if (child == child3) { #ifndef Q_OS_OSX @@ -3176,30 +3174,31 @@ class ContentsPropagationWidget : public QWidget { Q_OBJECT public: - ContentsPropagationWidget(QWidget *parent = 0) : QWidget(parent) + explicit ContentsPropagationWidget(QWidget *parent = nullptr) : QWidget(parent) { setObjectName(QLatin1String("ContentsPropagationWidget")); setWindowTitle(objectName()); QWidget *child = this; - for (int i=0; i<32; ++i) { + for (int i = 0; i < 32; ++i) { child = new QWidget(child); - child->setGeometry(i, i, 400 - i*2, 400 - i*2); + child->setGeometry(i, i, 400 - i * 2, 400 - i * 2); } } - void setContentsPropagation(bool enable) { - foreach (QObject *child, children()) + void setContentsPropagation(bool enable) + { + for (QObject *child : children()) qobject_cast<QWidget *>(child)->setAutoFillBackground(!enable); } protected: - void paintEvent(QPaintEvent *) + void paintEvent(QPaintEvent *) override { int w = width(), h = height(); drawPolygon(this, w, h); } - QSize sizeHint() const { return QSize(500, 500); } + QSize sizeHint() const override { return {500, 500}; } }; // Scale to remove devicePixelRatio should scaling be active. @@ -3273,6 +3272,7 @@ void tst_QWidget::saveRestoreGeometry() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); const QByteArray empty; const QByteArray one("a"); @@ -3384,7 +3384,7 @@ void tst_QWidget::restoreVersion1Geometry_data() if (m_platform == QStringLiteral("wayland")) QSKIP("Wayland: This fails. Figure out why."); QTest::addColumn<QString>("fileName"); - QTest::addColumn<uint>("expectedWindowState"); + QTest::addColumn<Qt::WindowState>("expectedWindowState"); QTest::addColumn<QPoint>("expectedPosition"); QTest::addColumn<QSize>("expectedSize"); QTest::addColumn<QRect>("expectedNormalGeometry"); @@ -3392,9 +3392,9 @@ void tst_QWidget::restoreVersion1Geometry_data() const QSize size(200, 200); const QRect normalGeometry(102, 124, 200, 200); - QTest::newRow("geometry.dat") << ":geometry.dat" << uint(Qt::WindowNoState) << position << size << normalGeometry; - QTest::newRow("geometry-maximized.dat") << ":geometry-maximized.dat" << uint(Qt::WindowMaximized) << position << size << normalGeometry; - QTest::newRow("geometry-fullscreen.dat") << ":geometry-fullscreen.dat" << uint(Qt::WindowFullScreen) << position << size << normalGeometry; + QTest::newRow("geometry.dat") << ":geometry.dat" << Qt::WindowNoState << position << size << normalGeometry; + QTest::newRow("geometry-maximized.dat") << ":geometry-maximized.dat" << Qt::WindowMaximized << position << size << normalGeometry; + QTest::newRow("geometry-fullscreen.dat") << ":geometry-fullscreen.dat" << Qt::WindowFullScreen << position << size << normalGeometry; } /* @@ -3404,14 +3404,14 @@ void tst_QWidget::restoreVersion1Geometry_data() void tst_QWidget::restoreVersion1Geometry() { QFETCH(QString, fileName); - QFETCH(uint, expectedWindowState); + QFETCH(Qt::WindowState, expectedWindowState); QFETCH(QPoint, expectedPosition); Q_UNUSED(expectedPosition); QFETCH(QSize, expectedSize); QFETCH(QRect, expectedNormalGeometry); // WindowActive is uninteresting for this test - const uint WindowStateMask = Qt::WindowFullScreen | Qt::WindowMaximized | Qt::WindowMinimized; + const Qt::WindowStates WindowStateMask = Qt::WindowFullScreen | Qt::WindowMaximized | Qt::WindowMinimized; QFile f(fileName); QVERIFY(f.exists()); @@ -3421,10 +3421,12 @@ void tst_QWidget::restoreVersion1Geometry() f.close(); QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("::") + + QLatin1String(QTest::currentDataTag())); QVERIFY(widget.restoreGeometry(savedGeometry)); - QCOMPARE(uint(widget.windowState() & WindowStateMask), expectedWindowState); + QCOMPARE(widget.windowState() & WindowStateMask, expectedWindowState); if (expectedWindowState == Qt::WindowNoState) { QTRY_COMPARE(widget.geometry(), expectedNormalGeometry); QCOMPARE(widget.size(), expectedSize); @@ -3488,11 +3490,11 @@ void tst_QWidget::widgetAt() Q_CHECK_PAINTEVENTS const QPoint referencePos = m_availableTopLeft + QPoint(100, 100); - QScopedPointer<QWidget> w1(new QWidget(0, Qt::X11BypassWindowManagerHint)); + QScopedPointer<QWidget> w1(new QWidget(nullptr, Qt::X11BypassWindowManagerHint)); w1->setGeometry(QRect(referencePos, QSize(m_testWidgetSize.width(), 150))); w1->setObjectName(QLatin1String("w1")); w1->setWindowTitle(w1->objectName()); - QScopedPointer<QWidget> w2(new QWidget(0, Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint)); + QScopedPointer<QWidget> w2(new QWidget(nullptr, Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint)); w2->setGeometry(QRect(referencePos + QPoint(50, 50), QSize(m_testWidgetSize.width(), 100))); w2->setObjectName(QLatin1String("w2")); w2->setWindowTitle(w2->objectName()); @@ -3552,6 +3554,7 @@ void tst_QWidget::widgetAt() void tst_QWidget::task110173() { QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QPushButton *pb1 = new QPushButton("click", &w); pb1->setFocusPolicy(Qt::ClickFocus); @@ -3569,20 +3572,20 @@ void tst_QWidget::task110173() class Widget : public QWidget { public: - Widget() : deleteThis(false) { setFocusPolicy(Qt::StrongFocus); } - void actionEvent(QActionEvent *) { if (deleteThis) delete this; } - void changeEvent(QEvent *) { if (deleteThis) delete this; } - void closeEvent(QCloseEvent *) { if (deleteThis) delete this; } - void hideEvent(QHideEvent *) { if (deleteThis) delete this; } - void focusOutEvent(QFocusEvent *) { if (deleteThis) delete this; } - void keyPressEvent(QKeyEvent *) { if (deleteThis) delete this; } - void keyReleaseEvent(QKeyEvent *) { if (deleteThis) delete this; } - void mouseDoubleClickEvent(QMouseEvent *) { if (deleteThis) delete this; } - void mousePressEvent(QMouseEvent *) { if (deleteThis) delete this; } - void mouseReleaseEvent(QMouseEvent *) { if (deleteThis) delete this; } - void mouseMoveEvent(QMouseEvent *) { if (deleteThis) delete this; } - - bool deleteThis; + Widget() { setFocusPolicy(Qt::StrongFocus); } + void actionEvent(QActionEvent *) override { if (deleteThis) delete this; } + void changeEvent(QEvent *) override { if (deleteThis) delete this; } + void closeEvent(QCloseEvent *) override { if (deleteThis) delete this; } + void hideEvent(QHideEvent *) override { if (deleteThis) delete this; } + void focusOutEvent(QFocusEvent *) override { if (deleteThis) delete this; } + void keyPressEvent(QKeyEvent *) override { if (deleteThis) delete this; } + void keyReleaseEvent(QKeyEvent *) override { if (deleteThis) delete this; } + void mouseDoubleClickEvent(QMouseEvent *) override { if (deleteThis) delete this; } + void mousePressEvent(QMouseEvent *) override { if (deleteThis) delete this; } + void mouseReleaseEvent(QMouseEvent *) override { if (deleteThis) delete this; } + void mouseMoveEvent(QMouseEvent *) override { if (deleteThis) delete this; } + + bool deleteThis = false; }; void tst_QWidget::testDeletionInEventHandlers() @@ -3631,7 +3634,7 @@ void tst_QWidget::testDeletionInEventHandlers() w = new Widget; w->show(); w->deleteThis = true; - QMouseEvent me(QEvent::MouseButtonRelease, QPoint(1, 1), Qt::LeftButton, Qt::LeftButton, 0); + QMouseEvent me(QEvent::MouseButtonRelease, QPoint(1, 1), Qt::LeftButton, Qt::LeftButton, Qt::KeyboardModifiers()); qApp->notify(w, &me); QVERIFY(w.isNull()); delete w; @@ -3735,21 +3738,19 @@ class StaticWidget : public QWidget { Q_OBJECT public: - bool partial; - bool gotPaintEvent; + bool partial = false; + bool gotPaintEvent = false; QRegion paintedRegion; - StaticWidget(QWidget *parent = 0) - :QWidget(parent) + explicit StaticWidget(QWidget *parent = nullptr) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); setAttribute(Qt::WA_OpaquePaintEvent); setPalette(Qt::red); // Make sure we have an opaque palette. setAutoFillBackground(true); - gotPaintEvent = false; } - void paintEvent(QPaintEvent *e) + void paintEvent(QPaintEvent *e) override { paintedRegion += e->region(); gotPaintEvent = true; @@ -3757,7 +3758,7 @@ public: // Look for a full update, set partial to false if found. for (QRect r : e->region()) { partial = (r != rect()); - if (partial == false) + if (!partial) break; } } @@ -3772,6 +3773,7 @@ void tst_QWidget::optimizedResizeMove() if (m_platform == QStringLiteral("wayland")) QSKIP("Wayland: This fails. Figure out why."); QWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.resize(400, 400); StaticWidget staticWidget(&parent); @@ -3853,6 +3855,7 @@ void tst_QWidget::optimizedResize_topLevel() if (QHighDpiScaling::isActive()) QSKIP("Skip due to rounding errors in the regions."); StaticWidget topLevel; + topLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); topLevel.gotPaintEvent = false; topLevel.show(); QVERIFY(QTest::qWaitForWindowExposed(&topLevel)); @@ -3897,7 +3900,7 @@ class SiblingDeleter : public QWidget public: inline SiblingDeleter(QWidget *sibling, QWidget *parent) : QWidget(parent), sibling(sibling) {} - inline virtual ~SiblingDeleter() { delete sibling; } + inline ~SiblingDeleter() { delete sibling; } private: QPointer<QWidget> sibling; @@ -3906,8 +3909,8 @@ private: void tst_QWidget::childDeletesItsSibling() { - QWidget *commonParent = new QWidget(0); - QPointer<QWidget> child = new QWidget(0); + auto commonParent = new QWidget(nullptr); + QPointer<QWidget> child(new QWidget(nullptr)); QPointer<QWidget> siblingDeleter = new SiblingDeleter(child, commonParent); child->setParent(commonParent); delete commonParent; // don't crash @@ -4042,15 +4045,12 @@ void tst_QWidget::ensureCreated() } } -class WinIdChangeWidget : public QWidget { +class WinIdChangeWidget : public QWidget +{ public: - WinIdChangeWidget(QWidget *p = 0) - : QWidget(p) - { - - } + using QWidget::QWidget; protected: - bool event(QEvent *e) + bool event(QEvent *e) override { if (e->type() == QEvent::WinIdChange) { m_winIdList.append(internalWinId()); @@ -4144,7 +4144,7 @@ void tst_QWidget::persistentWinId() WId winId3 = w3->winId(); // reparenting should preserve the winId of the widget being reparented and of its children - w1->setParent(0); + w1->setParent(nullptr); QCOMPARE(w1->winId(), winId1); QCOMPARE(w2->winId(), winId2); QCOMPARE(w3->winId(), winId3); @@ -4154,7 +4154,7 @@ void tst_QWidget::persistentWinId() QCOMPARE(w2->winId(), winId2); QCOMPARE(w3->winId(), winId3); - w2->setParent(0); + w2->setParent(nullptr); QCOMPARE(w2->winId(), winId2); QCOMPARE(w3->winId(), winId3); @@ -4166,7 +4166,7 @@ void tst_QWidget::persistentWinId() QCOMPARE(w2->winId(), winId2); QCOMPARE(w3->winId(), winId3); - w3->setParent(0); + w3->setParent(nullptr); QCOMPARE(w3->winId(), winId3); w3->setParent(w1); @@ -4207,26 +4207,20 @@ void tst_QWidget::showNativeChild() class ShowHideEventWidget : public QWidget { public: - int numberOfShowEvents, numberOfHideEvents; - int numberOfSpontaneousShowEvents, numberOfSpontaneousHideEvents; - - ShowHideEventWidget(QWidget *parent = 0) - : QWidget(parent) - , numberOfShowEvents(0), numberOfHideEvents(0) - , numberOfSpontaneousShowEvents(0), numberOfSpontaneousHideEvents(0) - { } + int numberOfShowEvents = 0, numberOfHideEvents = 0; + int numberOfSpontaneousShowEvents = 0, numberOfSpontaneousHideEvents = 0; - void create() - { QWidget::create(); } + using QWidget::QWidget; + using QWidget::create; - void showEvent(QShowEvent *e) + void showEvent(QShowEvent *e) override { ++numberOfShowEvents; if (e->spontaneous()) ++numberOfSpontaneousShowEvents; } - void hideEvent(QHideEvent *e) + void hideEvent(QHideEvent *e) override { ++numberOfHideEvents; if (e->spontaneous()) @@ -4289,6 +4283,7 @@ void tst_QWidget::showHideEvent() QFETCH(int, expectedHideEvents); ShowHideEventWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); if (show) widget.show(); if (hide) @@ -4351,13 +4346,14 @@ void tst_QWidget::showHideChildrenWhileMinimize_QTBUG50589() void tst_QWidget::update() { -#ifdef Q_OS_OSX +#ifdef Q_OS_MACOS QSKIP("QTBUG-52974"); #endif Q_CHECK_PAINTEVENTS UpdateWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.resize(100, 100); centerOnScreen(&w); w.show(); @@ -4609,14 +4605,14 @@ void tst_QWidget::scroll() updateWidget.reset(); updateWidget.move(QGuiApplication::primaryScreen()->geometry().center() - QPoint(250, 250)); updateWidget.showNormal(); - qApp->setActiveWindow(&updateWidget); + QApplication::setActiveWindow(&updateWidget); QVERIFY(QTest::qWaitForWindowActive(&updateWidget)); QVERIFY(updateWidget.numPaintEvents > 0); { updateWidget.reset(); updateWidget.scroll(10, 10); - qApp->processEvents(); + QCoreApplication::processEvents(); QRegion dirty(QRect(0, 0, w, 10)); dirty += QRegion(QRect(0, 10, 10, h - 10)); if (m_platform == QStringLiteral("winrt")) @@ -4628,7 +4624,7 @@ void tst_QWidget::scroll() updateWidget.reset(); updateWidget.update(0, 0, 10, 10); updateWidget.scroll(0, 10); - qApp->processEvents(); + QCoreApplication::processEvents(); QRegion dirty(QRect(0, 0, w, 10)); dirty += QRegion(QRect(0, 10, 10, 10)); QTRY_COMPARE(updateWidget.paintedRegion, dirty); @@ -4641,7 +4637,7 @@ void tst_QWidget::scroll() updateWidget.reset(); updateWidget.update(0, 0, 100, 100); updateWidget.scroll(10, 10, QRect(50, 50, 100, 100)); - qApp->processEvents(); + QCoreApplication::processEvents(); QRegion dirty(QRect(0, 0, 100, 50)); dirty += QRegion(QRect(0, 50, 150, 10)); dirty += QRegion(QRect(0, 60, 110, 40)); @@ -4654,7 +4650,7 @@ void tst_QWidget::scroll() updateWidget.reset(); updateWidget.update(0, 0, 100, 100); updateWidget.scroll(10, 10, QRect(100, 100, 100, 100)); - qApp->processEvents(); + QCoreApplication::processEvents(); QRegion dirty(QRect(0, 0, 100, 100)); dirty += QRegion(QRect(100, 100, 100, 10)); dirty += QRegion(QRect(100, 110, 10, 90)); @@ -4691,17 +4687,12 @@ class DestroyedSlotChecker : public QObject Q_OBJECT public: - bool wasQWidget; - - DestroyedSlotChecker() - : wasQWidget(false) - { - } + bool wasQWidget = false; public slots: void destroyedSlot(QObject *object) { - wasQWidget = (qobject_cast<QWidget *>(object) != 0 || object->isWidgetType()); + wasQWidget = (qobject_cast<QWidget *>(object) != nullptr || object->isWidgetType()); } }; @@ -4715,7 +4706,7 @@ void tst_QWidget::qobject_castInDestroyedSlot() QWidget *widget = new QWidget(); - QObject::connect(widget, SIGNAL(destroyed(QObject*)), &checker, SLOT(destroyedSlot(QObject*))); + QObject::connect(widget, &QObject::destroyed, &checker, &DestroyedSlotChecker::destroyedSlot); delete widget; QVERIFY(checker.wasQWidget); @@ -4724,62 +4715,53 @@ void tst_QWidget::qobject_castInDestroyedSlot() // Since X11 WindowManager operations are all async, and we have no way to know if the window // manager has finished playing with the window geometry, this test can't be reliable on X11. +using Rects = QVector<QRect>; + void tst_QWidget::setWindowGeometry_data() { - QTest::addColumn<QList<QRect> >("rects"); + QTest::addColumn<Rects>("rects"); QTest::addColumn<int>("windowFlags"); - QList<QList<QRect> > rects; + QVector<Rects> rects; const int width = m_testWidgetSize.width(); const int height = m_testWidgetSize.height(); const QRect availableAdjusted = QGuiApplication::primaryScreen()->availableGeometry().adjusted(100, 100, -100, -100); - rects << (QList<QRect>() - << QRect(m_availableTopLeft + QPoint(100, 100), m_testWidgetSize) - << availableAdjusted - << QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)) - << QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)) - << QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0))) - << (QList<QRect>() - << availableAdjusted - << QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)) - << QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)) - << QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)) - << QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height))) - << (QList<QRect>() - << QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)) - << QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)) - << QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)) - << QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height)) - << availableAdjusted) - << (QList<QRect>() - << QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)) - << QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)) - << QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height)) - << availableAdjusted - << QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height))) - << (QList<QRect>() - << QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)) - << QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height)) - << availableAdjusted - << QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)) - << QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0))); - - QList<int> windowFlags; - windowFlags << 0 << Qt::FramelessWindowHint; + rects << Rects{QRect(m_availableTopLeft + QPoint(100, 100), m_testWidgetSize), + availableAdjusted, + QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)), + QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)), + QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0))} + << Rects{availableAdjusted, + QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)), + QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)), + QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)), + QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height))} + << Rects{QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)), + QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)), + QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)), + QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height)), + availableAdjusted} + << Rects{QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0)), + QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)), + QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height)), + availableAdjusted, + QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height))} + << Rects{QRect(m_availableTopLeft + QPoint(130, 50), QSize(0, 0)), + QRect(m_availableTopLeft + QPoint(100, 100), QSize(width, height)), + availableAdjusted, + QRect(m_availableTopLeft + QPoint(130, 100), QSize(0, height)), + QRect(m_availableTopLeft + QPoint(100, 50), QSize(width, 0))}; + + const Qt::WindowFlags windowFlags[] = {Qt::WindowFlags(), Qt::FramelessWindowHint}; const bool skipEmptyRects = (m_platform == QStringLiteral("windows")); - foreach (QList<QRect> l, rects) { - QRect rect = l.first(); + for (Rects l : qAsConst(rects)) { if (skipEmptyRects) { - QList<QRect>::iterator it = l.begin(); - while (it != l.end()) { - if (it->isEmpty()) - it = l.erase(it); - else - ++it; - } + l.erase(std::remove_if(l.begin(), l.end(), [] (const QRect &r) { return r.isEmpty(); }), + l.end()); } - foreach (int windowFlag, windowFlags) { + const QRect &rect = l.constFirst(); + for (int windowFlag : windowFlags) { QTest::newRow(QString("%1,%2 %3x%4, flags %5") .arg(rect.x()) .arg(rect.y()) @@ -4799,7 +4781,7 @@ void tst_QWidget::setWindowGeometry() else if (m_platform == QStringLiteral("winrt")) QSKIP("WinRT does not support setWindowGeometry"); - QFETCH(QList<QRect>, rects); + QFETCH(Rects, rects); QFETCH(int, windowFlags); QRect rect = rects.takeFirst(); @@ -4814,7 +4796,7 @@ void tst_QWidget::setWindowGeometry() QCOMPARE(widget.geometry(), rect); // setGeometry() without showing - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.setGeometry(r); QTest::qWait(100); QCOMPARE(widget.geometry(), r); @@ -4824,6 +4806,7 @@ void tst_QWidget::setWindowGeometry() { // setGeometry() first, then show() QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); if (windowFlags != 0) widget.setWindowFlags(Qt::WindowFlags(windowFlags)); @@ -4839,7 +4822,7 @@ void tst_QWidget::setWindowGeometry() QTRY_COMPARE(widget.geometry(), rect); // setGeometry() while shown - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.setGeometry(r); QTest::qWait(10); QTRY_COMPARE(widget.geometry(), r); @@ -4854,7 +4837,7 @@ void tst_QWidget::setWindowGeometry() QTRY_COMPARE(widget.geometry(), rect); // setGeometry() after hide() - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.setGeometry(r); QTest::qWait(10); QTRY_COMPARE(widget.geometry(), r); @@ -4878,6 +4861,7 @@ void tst_QWidget::setWindowGeometry() { // show() first, then setGeometry() QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); if (windowFlags != 0) widget.setWindowFlags(Qt::WindowFlags(windowFlags)); @@ -4889,7 +4873,7 @@ void tst_QWidget::setWindowGeometry() QTRY_COMPARE(widget.geometry(), rect); // setGeometry() while shown - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.setGeometry(r); QTest::qWait(10); QTRY_COMPARE(widget.geometry(), r); @@ -4904,7 +4888,7 @@ void tst_QWidget::setWindowGeometry() QTRY_COMPARE(widget.geometry(), rect); // setGeometry() after hide() - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.setGeometry(r); QTest::qWait(10); QTRY_COMPARE(widget.geometry(), r); @@ -4967,7 +4951,7 @@ void tst_QWidget::windowMoveResize() if (m_platform == QStringLiteral("winrt")) QSKIP("WinRT does not support move/resize"); - QFETCH(QList<QRect>, rects); + QFETCH(Rects, rects); QFETCH(int, windowFlags); QRect rect = rects.takeFirst(); @@ -4985,7 +4969,7 @@ void tst_QWidget::windowMoveResize() QTRY_COMPARE(widget.size(), rect.size()); // move() without showing - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.move(r.topLeft()); widget.resize(r.size()); QApplication::processEvents(); @@ -4997,6 +4981,7 @@ void tst_QWidget::windowMoveResize() { // move() first, then show() QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); if (windowFlags != 0) widget.setWindowFlags(Qt::WindowFlags(windowFlags)); @@ -5013,7 +4998,7 @@ void tst_QWidget::windowMoveResize() QTRY_COMPARE(widget.size(), rect.size()); // move() while shown - foreach (const QRect &r, rects) { + for (const QRect &r : qAsConst(rects)) { // XCB: First resize after show of zero-sized gets wrong win_gravity. const bool expectMoveFail = !windowFlags && ((widget.width() == 0 || widget.height() == 0) && r.width() != 0 && r.height() != 0) @@ -5042,7 +5027,7 @@ void tst_QWidget::windowMoveResize() QTRY_COMPARE(widget.size(), rect.size()); // move() after hide() - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.move(r.topLeft()); widget.resize(r.size()); QApplication::processEvents(); @@ -5093,7 +5078,7 @@ void tst_QWidget::windowMoveResize() QTRY_COMPARE(widget.size(), rect.size()); // move() while shown - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.move(r.topLeft()); widget.resize(r.size()); QApplication::processEvents(); @@ -5113,7 +5098,7 @@ void tst_QWidget::windowMoveResize() QTRY_COMPARE(widget.size(), rect.size()); // move() after hide() - foreach (QRect r, rects) { + for (const QRect &r : qAsConst(rects)) { widget.move(r.topLeft()); widget.resize(r.size()); QApplication::processEvents(); @@ -5151,8 +5136,9 @@ void tst_QWidget::windowMoveResize() class ColorWidget : public QWidget { public: - ColorWidget(QWidget *parent = 0, Qt::WindowFlags f = 0, const QColor &c = QColor(Qt::red)) - : QWidget(parent, f), color(c), enters(0), leaves(0) + explicit ColorWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags(), + const QColor &c = QColor(Qt::red)) + : QWidget(parent, f), color(c) { QPalette opaquePalette = palette(); opaquePalette.setColor(backgroundRole(), color); @@ -5160,16 +5146,18 @@ public: setAutoFillBackground(true); } - void paintEvent(QPaintEvent *e) { + void paintEvent(QPaintEvent *e) override + { r += e->region(); } - void reset() { + void reset() + { r = QRegion(); } - void enterEvent(QEvent *) { ++enters; } - void leaveEvent(QEvent *) { ++leaves; } + void enterEvent(QEvent *) override { ++enters; } + void leaveEvent(QEvent *) override { ++leaves; } void resetCounts() { @@ -5179,8 +5167,8 @@ public: QColor color; QRegion r; - int enters; - int leaves; + int enters = 0; + int leaves = 0; }; static inline QByteArray msgRgbMismatch(unsigned actual, unsigned expected) @@ -5198,7 +5186,7 @@ static QPixmap grabWindow(QWindow *window, int x, int y, int width, int height) #define VERIFY_COLOR(child, region, color) verifyColor(child, region, color, __LINE__) -bool verifyColor(QWidget &child, const QRegion ®ion, const QColor &color, unsigned int callerLine) +bool verifyColor(QWidget &child, const QRegion ®ion, const QColor &color, int callerLine) { QWindow *window = child.window()->windowHandle(); Q_ASSERT(window); @@ -5224,16 +5212,13 @@ bool verifyColor(QWidget &child, const QRegion ®ion, const QColor &color, uns If it succeeds: return success If it fails: do not return, but wait a bit and reiterate (retry) */ - if (firstPixel == QColor(color).rgb() - && image == expectedPixmap.toImage()) { + if (firstPixel == QColor(color).rgb() && image == expectedPixmap.toImage()) return true; + if (t == 4) { + grabBackingStore = true; + rect = r; } else { - if (t == 4) { - grabBackingStore = true; - rect = r; - } else { - QTest::qWait(200); - } + QTest::qWait(200); } } else { // Last run, report failure if it still fails @@ -5269,7 +5254,7 @@ void tst_QWidget::moveChild() QSKIP("Wayland: This fails. Figure out why."); QFETCH(QPoint, offset); - ColorWidget parent(0, Qt::Window | Qt::WindowStaysOnTopHint); + ColorWidget parent(nullptr, Qt::Window | Qt::WindowStaysOnTopHint); // prevent custom styles const QScopedPointer<QStyle> style(QStyleFactory::create(QLatin1String("Windows"))); parent.setStyle(style.data()); @@ -5316,7 +5301,8 @@ void tst_QWidget::showAndMoveChild() { if (m_platform == QStringLiteral("wayland")) QSKIP("Wayland: This fails. Figure out why."); - QWidget parent(0, Qt::Window | Qt::WindowStaysOnTopHint); + QWidget parent(nullptr, Qt::Window | Qt::WindowStaysOnTopHint); + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); // prevent custom styles const QScopedPointer<QStyle> style(QStyleFactory::create(QLatin1String("Windows"))); parent.setStyle(style.data()); @@ -5331,7 +5317,7 @@ void tst_QWidget::showAndMoveChild() parent.setGeometry(desktopDimensions); parent.setPalette(Qt::red); parent.show(); - qApp->setActiveWindow(&parent); + QApplication::setActiveWindow(&parent); QVERIFY(QTest::qWaitForWindowActive(&parent)); QWidget child(&parent); @@ -5343,7 +5329,7 @@ void tst_QWidget::showAndMoveChild() // NB! Do NOT processEvents() (or qWait()) in between show() and move(). child.show(); child.move(desktopDimensions.width()/2, desktopDimensions.height()/2); - qApp->processEvents(); + QCoreApplication::processEvents(); if (m_platform == QStringLiteral("winrt")) QSKIP("WinRT does not support setGeometry (and we cannot use QEXPECT_FAIL because of VERIFY_COLOR)"); @@ -5359,6 +5345,7 @@ void tst_QWidget::subtractOpaqueSiblings() #endif QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setGeometry(50, 50, 300, 300); ColorWidget *large = new ColorWidget(&w, Qt::Widget, Qt::red); @@ -5392,10 +5379,11 @@ void tst_QWidget::subtractOpaqueSiblings() void tst_QWidget::deleteStyle() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.setStyle(QStyleFactory::create(QLatin1String("Windows"))); widget.show(); delete widget.style(); - qApp->processEvents(); + QCoreApplication::processEvents(); } class TopLevelFocusCheck: public QWidget @@ -5403,21 +5391,21 @@ class TopLevelFocusCheck: public QWidget Q_OBJECT public: QLineEdit* edit; - TopLevelFocusCheck(QWidget* parent = 0) : QWidget(parent) + explicit TopLevelFocusCheck(QWidget *parent = nullptr) + : QWidget(parent), edit(new QLineEdit(this)) { - edit = new QLineEdit(this); edit->hide(); edit->installEventFilter(this); } public slots: - void mouseDoubleClickEvent ( QMouseEvent * /*event*/ ) + void mouseDoubleClickEvent ( QMouseEvent * /*event*/ ) override { edit->show(); edit->setFocus(Qt::OtherFocusReason); - qApp->processEvents(); + QCoreApplication::processEvents(); } - bool eventFilter(QObject *obj, QEvent *event) + bool eventFilter(QObject *obj, QEvent *event) override { if (obj == edit && event->type()== QEvent::FocusOut) { edit->hide(); @@ -5464,7 +5452,7 @@ void tst_QWidget::multipleToplevelFocusCheck() QVERIFY(QTest::qWaitForWindowActive(&w2)); QCOMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&w2)); QTest::mouseClick(&w2, Qt::LeftButton); - QTRY_COMPARE(QApplication::focusWidget(), (QWidget *)0); + QTRY_COMPARE(QApplication::focusWidget(), nullptr); QTest::mouseDClick(&w2, Qt::LeftButton); QTRY_COMPARE(QApplication::focusWidget(), static_cast<QWidget *>(w2.edit)); @@ -5481,28 +5469,28 @@ void tst_QWidget::multipleToplevelFocusCheck() QVERIFY(QTest::qWaitForWindowActive(&w2)); QCOMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&w2)); QTest::mouseClick(&w2, Qt::LeftButton); - QTRY_COMPARE(QApplication::focusWidget(), (QWidget *)0); + QTRY_COMPARE(QApplication::focusWidget(), nullptr); } class FocusWidget: public QWidget { protected: - virtual bool event(QEvent *ev) + bool event(QEvent *ev) override { if (ev->type() == QEvent::FocusAboutToChange) - widgetDuringFocusAboutToChange = qApp->focusWidget(); + widgetDuringFocusAboutToChange = QApplication::focusWidget(); return QWidget::event(ev); } - virtual void focusInEvent(QFocusEvent *) + void focusInEvent(QFocusEvent *) override { - foucsObjectDuringFocusIn = qApp->focusObject(); - detectedBadEventOrdering = foucsObjectDuringFocusIn != mostRecentFocusObjectChange; + focusObjectDuringFocusIn = QGuiApplication::focusObject(); + detectedBadEventOrdering = focusObjectDuringFocusIn != mostRecentFocusObjectChange; } - virtual void focusOutEvent(QFocusEvent *) + void focusOutEvent(QFocusEvent *) override { - foucsObjectDuringFocusOut = qApp->focusObject(); - widgetDuringFocusOut = qApp->focusWidget(); - detectedBadEventOrdering = foucsObjectDuringFocusOut != mostRecentFocusObjectChange; + focusObjectDuringFocusOut = QGuiApplication::focusObject(); + widgetDuringFocusOut = QApplication::focusWidget(); + detectedBadEventOrdering = focusObjectDuringFocusOut != mostRecentFocusObjectChange; } void focusObjectChanged(QObject *focusObject) @@ -5511,22 +5499,19 @@ protected: } public: - FocusWidget(QWidget *parent) : QWidget(parent), - widgetDuringFocusAboutToChange(0), widgetDuringFocusOut(0), - foucsObjectDuringFocusIn(0), foucsObjectDuringFocusOut(0), - mostRecentFocusObjectChange(0), detectedBadEventOrdering(false) + explicit FocusWidget(QWidget *parent) : QWidget(parent) { connect(qGuiApp, &QGuiApplication::focusObjectChanged, this, &FocusWidget::focusObjectChanged); } - QWidget *widgetDuringFocusAboutToChange; - QWidget *widgetDuringFocusOut; + QWidget *widgetDuringFocusAboutToChange = nullptr; + QWidget *widgetDuringFocusOut = nullptr; - QObject *foucsObjectDuringFocusIn; - QObject *foucsObjectDuringFocusOut; + QObject *focusObjectDuringFocusIn = nullptr; + QObject *focusObjectDuringFocusOut = nullptr; - QObject *mostRecentFocusObjectChange; - bool detectedBadEventOrdering; + QObject *mostRecentFocusObjectChange = nullptr; + bool detectedBadEventOrdering = false; }; void tst_QWidget::setFocus() @@ -5623,7 +5608,7 @@ void tst_QWidget::setFocus() window.show(); window.activateWindow(); QVERIFY(QTest::qWaitForWindowExposed(&window)); - QTRY_VERIFY(qGuiApp->focusWindow()); + QTRY_VERIFY(QGuiApplication::focusWindow()); child1.setFocus(); QTRY_VERIFY(child1.hasFocus()); @@ -5650,7 +5635,7 @@ void tst_QWidget::setFocus() window.show(); window.activateWindow(); QVERIFY(QTest::qWaitForWindowExposed(&window)); - QTRY_VERIFY(qGuiApp->focusWindow()); + QTRY_VERIFY(QGuiApplication::focusWindow()); QWidget child1(&window); child1.setFocusPolicy(Qt::StrongFocus); @@ -5691,7 +5676,7 @@ void tst_QWidget::setFocus() window.show(); window.activateWindow(); QVERIFY(QTest::qWaitForWindowExposed(&window)); - QTRY_VERIFY(qGuiApp->focusWindow()); + QTRY_VERIFY(QGuiApplication::focusWindow()); QWidget child1(&window); child1.setFocusPolicy(Qt::StrongFocus); @@ -5732,6 +5717,7 @@ void tst_QWidget::setFocus() { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(m_testWidgetSize); window.move(windowPos); @@ -5750,7 +5736,7 @@ void tst_QWidget::setFocus() QCOMPARE(window.focusWidget(), &child1); QCOMPARE(QApplication::focusWidget(), &child1); QCOMPARE(QApplication::focusObject(), &child1); - QCOMPARE(child1.foucsObjectDuringFocusIn, &child1); + QCOMPARE(child1.focusObjectDuringFocusIn, &child1); QVERIFY2(!child1.detectedBadEventOrdering, "focusObjectChanged should be delivered before widget focus events on setFocus"); @@ -5759,7 +5745,7 @@ void tst_QWidget::setFocus() QCOMPARE(window.focusWidget(), nullptr); QCOMPARE(QApplication::focusWidget(), nullptr); QCOMPARE(QApplication::focusObject(), &window); - QVERIFY(child1.foucsObjectDuringFocusOut != &child1); + QVERIFY(child1.focusObjectDuringFocusOut != &child1); QVERIFY2(!child1.detectedBadEventOrdering, "focusObjectChanged should be delivered before widget focus events on clearFocus"); } @@ -5769,7 +5755,7 @@ template<class T> class EventSpy : public QObject { public: EventSpy(T *widget, QEvent::Type event) - : m_widget(widget), eventToSpy(event), m_count(0) + : m_widget(widget), eventToSpy(event) { if (m_widget) m_widget->installEventFilter(this); @@ -5780,7 +5766,7 @@ public: void clear() { m_count = 0; } protected: - bool eventFilter(QObject *object, QEvent *event) + bool eventFilter(QObject *object, QEvent *event) override { if (event->type() == eventToSpy) ++m_count; @@ -5789,8 +5775,8 @@ protected: private: T *m_widget; - QEvent::Type eventToSpy; - int m_count; + const QEvent::Type eventToSpy; + int m_count = 0; }; #ifndef QT_NO_CURSOR @@ -5813,6 +5799,7 @@ void tst_QWidget::setCursor() // do it again, but with window show()n { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget child(&window); window.show(); @@ -5841,6 +5828,7 @@ void tst_QWidget::setCursor() // same thing again, just with window show()n { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget child(&window); @@ -5862,7 +5850,7 @@ void tst_QWidget::setCursor() window.setCursor(Qt::WaitCursor); - child.setParent(0); + child.setParent(nullptr); QVERIFY(!child.testAttribute(Qt::WA_SetCursor)); QCOMPARE(child.cursor().shape(), QCursor().shape()); @@ -5878,6 +5866,7 @@ void tst_QWidget::setCursor() // again, with windows show()n { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(200, 200); QWidget window2; window2.resize(200, 200); @@ -5886,7 +5875,7 @@ void tst_QWidget::setCursor() window.setCursor(Qt::WaitCursor); window.show(); - child.setParent(0); + child.setParent(nullptr); QVERIFY(!child.testAttribute(Qt::WA_SetCursor)); QCOMPARE(child.cursor().shape(), QCursor().shape()); @@ -5938,7 +5927,7 @@ void tst_QWidget::setToolTip() for (int pass = 0; pass < 2; ++pass) { QCursor::setPos(m_safeCursorPos); - QScopedPointer<QWidget> popup(new QWidget(0, Qt::Popup)); + QScopedPointer<QWidget> popup(new QWidget(nullptr, Qt::Popup)); popup->setObjectName(QLatin1String("tst_qwidget setToolTip #") + QString::number(pass)); popup->setWindowTitle(popup->objectName()); popup->setGeometry(50, 50, 150, 50); @@ -5947,7 +5936,7 @@ void tst_QWidget::setToolTip() frame->setFrameStyle(QFrame::Box | QFrame::Plain); EventSpy<QWidget> spy1(frame, QEvent::ToolTip); EventSpy<QWidget> spy2(popup.data(), QEvent::ToolTip); - frame->setMouseTracking(pass == 0 ? false : true); + frame->setMouseTracking(pass != 0); frame->setToolTip(QLatin1String("TOOLTIP FRAME")); popup->setToolTip(QLatin1String("TOOLTIP POPUP")); popup->show(); @@ -6001,13 +5990,13 @@ void tst_QWidget::testWindowIconChangeEventPropagation() // Create spy lists. QList <EventSpyPtr> applicationEventSpies; QList <EventSpyPtr> widgetEventSpies; - foreach (QWidget *widget, widgets) { + for (QWidget *widget : qAsConst(widgets)) { applicationEventSpies.append(EventSpyPtr::create(widget, QEvent::ApplicationWindowIconChange)); widgetEventSpies.append(EventSpyPtr::create(widget, QEvent::WindowIconChange)); } QList <WindowEventSpyPtr> appWindowEventSpies; QList <WindowEventSpyPtr> windowEventSpies; - foreach (QWindow *window, windows) { + for (QWindow *window : qAsConst(windows)) { appWindowEventSpies.append(WindowEventSpyPtr::create(window, QEvent::ApplicationWindowIconChange)); windowEventSpies.append(WindowEventSpyPtr::create(window, QEvent::WindowIconChange)); } @@ -6084,7 +6073,8 @@ void tst_QWidget::minAndMaxSizeWithX11BypassWindowManagerHint() const QSize originalSize(desktopSize.width() / 2, desktopSize.height() * 4 / 10); { // Maximum size. - QWidget widget(0, Qt::X11BypassWindowManagerHint); + QWidget widget(nullptr, Qt::X11BypassWindowManagerHint); + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); const QSize newMaximumSize = widget.size().boundedTo(originalSize) - QSize(10, 10); widget.setMaximumSize(newMaximumSize); @@ -6096,7 +6086,8 @@ void tst_QWidget::minAndMaxSizeWithX11BypassWindowManagerHint() } { // Minimum size. - QWidget widget(0, Qt::X11BypassWindowManagerHint); + QWidget widget(nullptr, Qt::X11BypassWindowManagerHint); + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); const QSize newMinimumSize = widget.size().expandedTo(originalSize) + QSize(10, 10); widget.setMinimumSize(newMinimumSize); @@ -6112,13 +6103,12 @@ class ShowHideShowWidget : public QWidget, public QAbstractNativeEventFilter { Q_OBJECT - int state; + int state = 0; public: - bool gotExpectedMapNotify; - bool gotExpectedGlobalEvent; + bool gotExpectedMapNotify = false; + bool gotExpectedGlobalEvent = false; ShowHideShowWidget() - : state(0), gotExpectedMapNotify(false), gotExpectedGlobalEvent(false) { startTimer(1000); } @@ -6140,7 +6130,7 @@ public: enum { XCB_MAP_NOTIFY = 19 }; if (state == 1 && eventType == QByteArrayLiteral("xcb_generic_event_t")) { // XCB events have a uint8 response_type member at the beginning. - const unsigned char responseType = *(const unsigned char *)(message); + const auto responseType = *reinterpret_cast<const unsigned char *>(message); return ((responseType & ~0x80) == XCB_MAP_NOTIFY); } return false; @@ -6179,6 +6169,7 @@ void tst_QWidget::showHideShowX11() QSKIP("This test is for X11 only."); ShowHideShowWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); qApp->installNativeEventFilter(&w); w.show(); @@ -6186,7 +6177,7 @@ void tst_QWidget::showHideShowX11() w.hide(); QEventLoop eventLoop; - connect(&w, SIGNAL(done()), &eventLoop, SLOT(quit())); + connect(&w, &ShowHideShowWidget::done, &eventLoop, &QEventLoop::quit); eventLoop.exec(); QVERIFY(w.gotExpectedGlobalEvent); @@ -6200,6 +6191,7 @@ void tst_QWidget::clean_qt_x11_enforce_cursor() { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget *w = new QWidget(&window); QWidget *child = new QWidget(w); child->setAttribute(Qt::WA_SetCursor, true); @@ -6233,11 +6225,9 @@ public: typedef QPair<QWidget *, QEvent::Type> WidgetEventTypePair; typedef QList<WidgetEventTypePair> EventList; - EventRecorder(QObject *parent = 0) - : QObject(parent) - { } + using QObject::QObject; - EventList eventList() + EventList eventList() const { return events; } @@ -6247,7 +6237,7 @@ public: events.clear(); } - bool eventFilter(QObject *object, QEvent *event) + bool eventFilter(QObject *object, QEvent *event) override { QWidget *widget = qobject_cast<QWidget *>(object); if (widget && !event->spontaneous()) @@ -6267,8 +6257,8 @@ private: void EventRecorder::formatEventList(const EventList &l, QDebug &d) { - QWidget *lastWidget = 0; - foreach (const WidgetEventTypePair &p, l) { + QWidget *lastWidget = nullptr; + for (const WidgetEventTypePair &p : l) { if (p.first != lastWidget) { d << p.first << ':'; lastWidget = p.first; @@ -6460,7 +6450,7 @@ void tst_QWidget::childEvents() QWidget child1(&widget); QWidget child2; child2.setParent(&widget); - child2.setParent(0); + child2.setParent(nullptr); QCoreApplication::postEvent(&widget, new QEvent(QEvent::Type(QEvent::User + 2))); @@ -6497,7 +6487,7 @@ void tst_QWidget::childEvents() QWidget child1(&widget); QWidget child2; child2.setParent(&widget); - child2.setParent(0); + child2.setParent(nullptr); QCoreApplication::postEvent(&widget, new QEvent(QEvent::Type(QEvent::User + 2))); @@ -6577,6 +6567,7 @@ void tst_QWidget::render() { return; QCalendarWidget source; + source.setWindowTitle(QLatin1String(QTest::currentTestFunction())); // disable anti-aliasing to eliminate potential differences when subpixel antialiasing // is enabled on the screen QFont f; @@ -6590,22 +6581,22 @@ void tst_QWidget::render() target.resize(source.size()); target.show(); - qApp->processEvents(); - qApp->sendPostedEvents(); + QCoreApplication::processEvents(); + QCoreApplication::sendPostedEvents(); QTest::qWait(250); const QImage sourceImage = source.grab(QRect(QPoint(0, 0), QSize(-1, -1))).toImage(); - qApp->processEvents(); + QCoreApplication::processEvents(); QImage targetImage = target.grab(QRect(QPoint(0, 0), QSize(-1, -1))).toImage(); - qApp->processEvents(); + QCoreApplication::processEvents(); QCOMPARE(sourceImage, targetImage); // Fill target.rect() will Qt::red and render // QRegion(0, 0, source->width(), source->height() / 2, QRegion::Ellipse) // of source into target with offset (0, 30). target.setEllipseEnabled(); - qApp->processEvents(); - qApp->sendPostedEvents(); + QCoreApplication::processEvents(); + QCoreApplication::sendPostedEvents(); targetImage = target.grab(QRect(QPoint(0, 0), QSize(-1, -1))).toImage(); QVERIFY(sourceImage != targetImage); @@ -6616,6 +6607,7 @@ void tst_QWidget::render() // Test that a child widget properly fills its background { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(100, 100); // prevent custom styles window.setStyle(QStyleFactory::create(QLatin1String("Windows"))); @@ -6625,7 +6617,7 @@ void tst_QWidget::render() child.resize(window.size()); child.show(); - qApp->processEvents(); + QCoreApplication::processEvents(); const QPixmap childPixmap = child.grab(QRect(QPoint(0, 0), QSize(-1, -1))); const QPixmap windowPixmap = window.grab(QRect(QPoint(0, 0), QSize(-1, -1))); QCOMPARE(childPixmap, windowPixmap); @@ -6633,6 +6625,7 @@ void tst_QWidget::render() { // Check that the target offset is correct. QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(200, 200); widget.setAutoFillBackground(true); widget.setPalette(Qt::red); @@ -6693,6 +6686,7 @@ void tst_QWidget::renderInvisible() QScopedPointer<QCalendarWidget> calendar(new QCalendarWidget); calendar->move(m_availableTopLeft + QPoint(100, 100)); + calendar->setWindowTitle(QLatin1String(QTest::currentTestFunction())); // disable anti-aliasing to eliminate potential differences when subpixel antialiasing // is enabled on the screen QFont f; @@ -6707,7 +6701,7 @@ void tst_QWidget::renderInvisible() dummyFocusWidget.move(calendar->geometry().bottomLeft() + QPoint(0, 100)); dummyFocusWidget.show(); QVERIFY(QTest::qWaitForWindowExposed(&dummyFocusWidget)); - qApp->processEvents(); + QCoreApplication::processEvents(); QTest::qWait(120); // Create normal reference image. @@ -6722,7 +6716,7 @@ void tst_QWidget::renderInvisible() // Create resized reference image. const QSize calendarSizeResized = calendar->size() + QSize(50, 50); calendar->resize(calendarSizeResized); - qApp->processEvents(); + QCoreApplication::processEvents(); QTest::qWait(30); QImage referenceImageResized(calendarSizeResized, QImage::Format_ARGB32); calendar->render(&referenceImageResized); @@ -6733,7 +6727,7 @@ void tst_QWidget::renderInvisible() // Explicitly hide the calendar. calendar->hide(); - qApp->processEvents(); + QCoreApplication::processEvents(); QTest::qWait(30); workaroundPaletteIssue(calendar.data()); @@ -6763,7 +6757,7 @@ void tst_QWidget::renderInvisible() } calendar->hide(); - qApp->processEvents(); + QCoreApplication::processEvents(); QTest::qWait(30); { // Calendar explicitly hidden. @@ -6831,7 +6825,7 @@ void tst_QWidget::renderInvisible() // Navigation bar isn't explicitly hidden anymore. navigationBar->show(); - qApp->processEvents(); + QCoreApplication::processEvents(); QTest::qWait(30); QVERIFY(!calendar->isVisible()); @@ -6840,7 +6834,7 @@ void tst_QWidget::renderInvisible() // make sure the layout is activated before rendering. QVERIFY(!calendar->isVisible()); calendar->resize(calendarSizeResized); - qApp->processEvents(); + QCoreApplication::processEvents(); { // Make sure we get an image equal to the resized reference image. QImage testImage(calendarSizeResized, QImage::Format_ARGB32); @@ -6893,7 +6887,7 @@ void tst_QWidget::renderInvisible() void tst_QWidget::renderWithPainter() { - QWidget widget(0, Qt::Tool); + QWidget widget(nullptr, Qt::Tool); // prevent custom styles const QScopedPointer<QStyle> style(QStyleFactory::create(QLatin1String("Windows"))); @@ -7009,7 +7003,7 @@ void tst_QWidget::render_task211796() { class MyWidget : public QWidget { - void resizeEvent(QResizeEvent *) + void resizeEvent(QResizeEvent *) override { QPixmap pixmap(size()); render(&pixmap); @@ -7018,6 +7012,7 @@ void tst_QWidget::render_task211796() { // Please don't die in a resize recursion. MyWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(m_testWidgetSize); centerOnScreen(&widget); widget.show(); @@ -7025,6 +7020,7 @@ void tst_QWidget::render_task211796() { // Same check with a deeper hierarchy. QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(m_testWidgetSize); centerOnScreen(&widget); widget.show(); @@ -7093,19 +7089,19 @@ void tst_QWidget::render_windowOpacity() class MyWidget : public QWidget { public: - void paintEvent(QPaintEvent *) + explicit MyWidget(qreal opacityIn) : opacity(opacityIn) {} + void paintEvent(QPaintEvent *) override { QPainter painter(this); painter.setOpacity(opacity); QCOMPARE(painter.opacity(), opacity); painter.fillRect(rect(), Qt::red); } - qreal opacity; + const qreal opacity; }; - MyWidget widget; + MyWidget widget(opacity); widget.resize(50, 50); - widget.opacity = opacity; widget.setPalette(Qt::blue); widget.setAutoFillBackground(true); @@ -7242,16 +7238,16 @@ void tst_QWidget::render_systemClip2() class MyWidget : public QWidget { public: - bool usePaintEvent; - void paintEvent(QPaintEvent *) + explicit MyWidget(bool usePaintEventIn) : usePaintEvent(usePaintEventIn) {} + const bool usePaintEvent; + void paintEvent(QPaintEvent *) override { if (usePaintEvent) QPainter(this).fillRect(rect(), Qt::green); } }; - MyWidget widget; - widget.usePaintEvent = usePaintEvent; + MyWidget widget(usePaintEvent); widget.setPalette(Qt::blue); // NB! widget.setAutoFillBackground(autoFillBackground) won't do the // trick here since the widget is a top-level. The background is filled @@ -7347,7 +7343,6 @@ void tst_QWidget::render_systemClip3() const QRegion redArea(QRegion(0, 0, size.width(), size.height()) - outerCross); const QRegion whiteArea(outerCross - innerCross); - const QRegion blueArea(innerCross); QRegion systemClip; // Okay, here's the image that should look like a Norwegian civil/war flag in the end. @@ -7373,8 +7368,9 @@ void tst_QWidget::render_systemClip3() // The outer cross (white) should be drawn when the background is auto-filled, and // the inner cross (blue) should be drawn in the paintEvent. class MyWidget : public QWidget - { public: - void paintEvent(QPaintEvent *) + { + public: + void paintEvent(QPaintEvent *) override { QPainter painter(this); // Be evil and try to paint outside the outer cross. This should not be @@ -7429,8 +7425,9 @@ void tst_QWidget::render_task252837() void tst_QWidget::render_worldTransform() { class MyWidget : public QWidget - { public: - void paintEvent(QPaintEvent *) + { + public: + void paintEvent(QPaintEvent *) override { QPainter painter(this); // Make sure world transform is identity. @@ -7524,6 +7521,7 @@ void tst_QWidget::setContentsMargins() QVERIFY2(oldSize != newSize, msgComparisonFailed(oldSize, "!=", newSize)); QLabel label2("why does it always rain on me?"); + label2.setWindowTitle(QLatin1String(QTest::currentTestFunction())); label2.show(); label2.setFrameStyle(QFrame::Sunken | QFrame::Box); QCOMPARE(newSize, label2.sizeHint()); @@ -7556,7 +7554,7 @@ void tst_QWidget::moveWindowInShowEvent() { public: QPoint position; - void showEvent(QShowEvent *) + void showEvent(QShowEvent *) override { move(position); } @@ -7587,7 +7585,8 @@ void tst_QWidget::repaintWhenChildDeleted() QTest::qWait(1000); } #endif - ColorWidget w(0, Qt::FramelessWindowHint, Qt::red); + ColorWidget w(nullptr, Qt::FramelessWindowHint, Qt::red); + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QPoint startPoint = QApplication::desktop()->availableGeometry(&w).topLeft(); startPoint.rx() += 50; startPoint.ry() += 50; @@ -7611,7 +7610,8 @@ void tst_QWidget::repaintWhenChildDeleted() // task 175114 void tst_QWidget::hideOpaqueChildWhileHidden() { - ColorWidget w(0, Qt::FramelessWindowHint, Qt::red); + ColorWidget w(nullptr, Qt::FramelessWindowHint, Qt::red); + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QPoint startPoint = QApplication::desktop()->availableGeometry(&w).topLeft(); startPoint.rx() += 50; startPoint.ry() += 50; @@ -7654,6 +7654,7 @@ void tst_QWidget::updateWhileMinimized() QSKIP("Platform does not support showMinimized()"); #endif UpdateWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); // Filter out activation change and focus events to avoid update() calls in QWidget. widget.updateOnActivationChangeAndFocusIn = false; widget.reset(); @@ -7685,13 +7686,10 @@ void tst_QWidget::updateWhileMinimized() class PaintOnScreenWidget: public QWidget { public: - PaintOnScreenWidget(QWidget *parent = 0, Qt::WindowFlags f = 0) - :QWidget(parent, f) - { - } + using QWidget::QWidget; #if defined(Q_OS_WIN) // This is the only way to enable PaintOnScreen on Windows. - QPaintEngine * paintEngine () const {return 0;} + QPaintEngine *paintEngine() const override { return nullptr; } #endif }; @@ -7702,6 +7700,7 @@ void tst_QWidget::alienWidgets() qApp->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); QWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.resize(m_testWidgetSize); QWidget child(&parent); QWidget grandChild(&child); @@ -7736,6 +7735,7 @@ void tst_QWidget::alienWidgets() // Ensure that hide() on an ancestor of a widget with // Qt::WA_DontCreateNativeAncestors still gets unmapped QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(m_testWidgetSize); QWidget widget(&window); QWidget child(&widget); @@ -7779,6 +7779,7 @@ void tst_QWidget::alienWidgets() // Check that widgets with the Qt::MSWindowsOwnDC attribute set // are native. QWidget msWindowsOwnDC(&parent, Qt::MSWindowsOwnDC); + msWindowsOwnDC.setWindowTitle(QLatin1String(QTest::currentTestFunction())); msWindowsOwnDC.show(); QVERIFY(msWindowsOwnDC.testAttribute(Qt::WA_WState_Created)); QVERIFY(msWindowsOwnDC.testAttribute(Qt::WA_NativeWindow)); @@ -7807,6 +7808,7 @@ void tst_QWidget::alienWidgets() { // Make sure we create native ancestors when setting Qt::WA_PaintOnScreen before show(). QWidget topLevel; + topLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); topLevel.resize(m_testWidgetSize); QWidget child(&topLevel); QWidget grandChild(&child); @@ -7831,6 +7833,7 @@ void tst_QWidget::alienWidgets() { // Ensure that widgets reparented into Qt::WA_PaintOnScreen widgets become native. QWidget topLevel; + topLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); topLevel.resize(m_testWidgetSize); QWidget *widget = new PaintOnScreenWidget(&topLevel); widget->setAttribute(Qt::WA_PaintOnScreen); @@ -7864,6 +7867,7 @@ void tst_QWidget::alienWidgets() { // Ensure that ancestors of a Qt::WA_PaintOnScreen widget stay native // if they are re-created (typically in QWidgetPrivate::setParent_sys) (task 210822). QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.resize(m_testWidgetSize); QWidget child(&window); @@ -7902,6 +7906,7 @@ void tst_QWidget::alienWidgets() { // Ensure that all siblings are native unless Qt::AA_DontCreateNativeWidgetSiblings is set. qApp->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, false); QWidget mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget *toolBar = new QWidget(&mainWindow); QWidget *dockWidget = new QWidget(&mainWindow); QWidget *centralWidget = new QWidget(&mainWindow); @@ -7936,7 +7941,7 @@ void tst_QWidget::alienWidgets() class ASWidget : public QWidget { public: - ASWidget(QSize sizeHint, QSizePolicy sizePolicy, bool layout, bool hfwLayout, QWidget *parent = 0) + ASWidget(QSize sizeHint, QSizePolicy sizePolicy, bool layout, bool hfwLayout, QWidget *parent = nullptr) : QWidget(parent), mySizeHint(sizeHint) { setObjectName(QStringLiteral("ASWidget")); @@ -7953,17 +7958,15 @@ public: } } - QSize sizeHint() const { + QSize sizeHint() const override + { if (layout()) return layout()->totalSizeHint(); return mySizeHint; } - int heightForWidth(int width) const { - if (sizePolicy().hasHeightForWidth()) { - return width * 2; - } else { - return -1; - } + int heightForWidth(int width) const override + { + return sizePolicy().hasHeightForWidth() ? width * 2 : -1; } QSize mySizeHint; @@ -8038,7 +8041,7 @@ void tst_QWidget::adjustSize() QSizePolicy sp = QSizePolicy(QSizePolicy::Policy(hPolicy), QSizePolicy::Policy(vPolicy)); sp.setHeightForWidth(hfwSP); - QWidget *child = new ASWidget(sizeHint, sp, layout, hfwLayout, haveParent ? parent.data() : 0); + QWidget *child = new ASWidget(sizeHint, sp, layout, hfwLayout, haveParent ? parent.data() : nullptr); child->resize(123, 456); child->adjustSize(); if (expectedSize == QSize(100000, 100000)) { @@ -8057,17 +8060,14 @@ class TestLayout : public QVBoxLayout { Q_OBJECT public: - TestLayout(QWidget *w = 0) : QVBoxLayout(w) - { - invalidated = false; - } + using QVBoxLayout::QVBoxLayout; - void invalidate() + void invalidate() override { invalidated = true; } - bool invalidated; + bool invalidated = false; }; void tst_QWidget::updateGeometry_data() @@ -8076,7 +8076,7 @@ void tst_QWidget::updateGeometry_data() QTest::addColumn<bool>("shouldInvalidate"); QTest::addColumn<QSize>("maxSize"); QTest::addColumn<bool>("shouldInvalidate2"); - QTest::addColumn<int>("verticalSizePolicy"); + QTest::addColumn<QSizePolicy::Policy>("verticalSizePolicy"); QTest::addColumn<bool>("shouldInvalidate3"); QTest::addColumn<bool>("setVisible"); QTest::addColumn<bool>("shouldInvalidate4"); @@ -8084,32 +8084,32 @@ void tst_QWidget::updateGeometry_data() QTest::newRow("setMinimumSize") << QSize(100, 100) << true << QSize() << false - << int(QSizePolicy::Preferred) << false + << QSizePolicy::Preferred << false << true << false; QTest::newRow("setMaximumSize") << QSize() << false << QSize(100, 100) << true - << int(QSizePolicy::Preferred) << false + << QSizePolicy::Preferred << false << true << false; QTest::newRow("setMinimumSize, then maximumSize to a different size") << QSize(100, 100) << true << QSize(300, 300) << true - << int(QSizePolicy::Preferred) << false + << QSizePolicy::Preferred << false << true << false; QTest::newRow("setMinimumSize, then maximumSize to the same size") << QSize(100, 100) << true << QSize(100, 100) << true - << int(QSizePolicy::Preferred) << false + << QSizePolicy::Preferred << false << true << false; QTest::newRow("setMinimumSize, then maximumSize to the same size and then hide it") << QSize(100, 100) << true << QSize(100, 100) << true - << int(QSizePolicy::Preferred) << false + << QSizePolicy::Preferred << false << false << true; QTest::newRow("Change sizePolicy") << QSize() << false << QSize() << false - << int(QSizePolicy::Minimum) << true + << QSizePolicy::Minimum << true << true << false; } @@ -8120,11 +8120,13 @@ void tst_QWidget::updateGeometry() QFETCH(bool, shouldInvalidate); QFETCH(QSize, maxSize); QFETCH(bool, shouldInvalidate2); - QFETCH(int, verticalSizePolicy); + QFETCH(QSizePolicy::Policy, verticalSizePolicy); QFETCH(bool, shouldInvalidate3); QFETCH(bool, setVisible); QFETCH(bool, shouldInvalidate4); QWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1String("::") + + QLatin1String(QTest::currentDataTag())); parent.resize(200, 200); TestLayout *lout = new TestLayout(); parent.setLayout(lout); @@ -8144,7 +8146,7 @@ void tst_QWidget::updateGeometry() QCOMPARE(lout->invalidated, shouldInvalidate2); lout->invalidated = false; - child->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, (QSizePolicy::Policy)verticalSizePolicy)); + child->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, verticalSizePolicy)); if (shouldInvalidate3) QCOMPARE(lout->invalidated, true); @@ -8157,11 +8159,12 @@ void tst_QWidget::updateGeometry() void tst_QWidget::sendUpdateRequestImmediately() { UpdateWidget updateWidget; + updateWidget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); updateWidget.show(); QVERIFY(QTest::qWaitForWindowExposed(&updateWidget)); - qApp->processEvents(); + QCoreApplication::processEvents(); updateWidget.reset(); QCOMPARE(updateWidget.numUpdateRequestEvents, 0); @@ -8180,6 +8183,7 @@ void tst_QWidget::doubleRepaint() QSKIP("Not having window server access causes the wrong number of repaints to be issues"); #endif UpdateWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); centerOnScreen(&widget); widget.setFocusPolicy(Qt::StrongFocus); // Filter out activation change and focus events to avoid update() calls in QWidget. @@ -8213,10 +8217,11 @@ void tst_QWidget::doubleRepaint() void tst_QWidget::resizeInPaintEvent() { QWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); UpdateWidget widget(&window); window.resize(200, 200); window.show(); - qApp->setActiveWindow(&window); + QApplication::setActiveWindow(&window); QVERIFY(QTest::qWaitForWindowExposed(&window)); QTRY_VERIFY(widget.numPaintEvents > 0); @@ -8237,6 +8242,7 @@ void tst_QWidget::resizeInPaintEvent() void tst_QWidget::opaqueChildren() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(200, 200); QWidget child(&widget); @@ -8277,10 +8283,10 @@ class MaskSetWidget : public QWidget { Q_OBJECT public: - MaskSetWidget(QWidget* p =0) - : QWidget(p) {} + using QWidget::QWidget; - void paintEvent(QPaintEvent* event) { + void paintEvent(QPaintEvent *event) override + { QPainter p(this); paintedRegion += event->region(); @@ -8288,26 +8294,22 @@ public: p.fillRect(r, Qt::red); } - void resizeEvent(QResizeEvent*) { + void resizeEvent(QResizeEvent *) override + { setMask(QRegion(QRect(0, 0, width(), 10).normalized())); } QRegion paintedRegion; public slots: - void resizeDown() { - setGeometry(QRect(0, 50, 50, 50)); - } - - void resizeUp() { - setGeometry(QRect(0, 50, 150, 50)); - } - + void resizeDown() { setGeometry(QRect(0, 50, 50, 50)); } + void resizeUp() { setGeometry(QRect(0, 50, 150, 50)); } }; void tst_QWidget::setMaskInResizeEvent() { UpdateWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.reset(); w.resize(200, 200); centerOnScreen(&w); @@ -8346,19 +8348,19 @@ class MoveInResizeWidget : public QWidget { Q_OBJECT public: - MoveInResizeWidget(QWidget* p = 0) + explicit MoveInResizeWidget(QWidget *p = nullptr) : QWidget(p) { setWindowFlags(Qt::FramelessWindowHint); } - void resizeEvent(QResizeEvent*) { - + void resizeEvent(QResizeEvent *) override + { move(QPoint(100,100)); static bool firstTime = true; if (firstTime) - QTimer::singleShot(250, this, SLOT(resizeMe())); + QTimer::singleShot(250, this, &MoveInResizeWidget::resizeMe); firstTime = false; } @@ -8372,6 +8374,7 @@ public slots: void tst_QWidget::moveInResizeEvent() { MoveInResizeWidget testWidget; + testWidget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); testWidget.setGeometry(50, 50, 200, 200); testWidget.show(); QVERIFY(QTest::qWaitForWindowExposed(&testWidget)); @@ -8387,6 +8390,7 @@ void tst_QWidget::immediateRepaintAfterInvalidateBackingStore() QSKIP("We don't support immediate repaint right after show on other platforms."); QScopedPointer<UpdateWidget> widget(new UpdateWidget); + widget->setWindowTitle(QLatin1String(QTest::currentTestFunction())); centerOnScreen(widget.data()); widget->show(); QVERIFY(QTest::qWaitForWindowExposed(widget.data())); @@ -8409,6 +8413,7 @@ void tst_QWidget::immediateRepaintAfterInvalidateBackingStore() void tst_QWidget::effectiveWinId() { QWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.resize(200, 200); QWidget child(&parent); @@ -8426,8 +8431,9 @@ void tst_QWidget::effectiveWinId2() { QWidget parent; - class MyWidget : public QWidget { - bool event(QEvent *e) + class MyWidget : public QWidget + { + bool event(QEvent *e) override { if (e->type() == QEvent::WinIdChange) { // Shouldn't crash. @@ -8442,18 +8448,19 @@ void tst_QWidget::effectiveWinId2() child.setParent(&parent); parent.show(); - child.setParent(0); + child.setParent(nullptr); child.setParent(&parent); } class CustomWidget : public QWidget { public: - mutable int metricCallCount; + mutable int metricCallCount = 0; - CustomWidget(QWidget *parent = 0) : QWidget(parent), metricCallCount(0) {} + using QWidget::QWidget; - virtual int metric(PaintDeviceMetric metric) const { + int metric(PaintDeviceMetric metric) const override + { ++metricCallCount; return QWidget::metric(metric); } @@ -8547,6 +8554,7 @@ void tst_QWidget::quitOnCloseAttribute() void tst_QWidget::moveRect() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(200, 200); widget.setUpdatesEnabled(false); QWidget child(&widget); @@ -8567,11 +8575,12 @@ public: timer.setSingleShot(true); timer.setInterval(0); } - QPaintEngine *paintEngine() const { return 0; } + QPaintEngine *paintEngine() const override { return nullptr; } - void paintEvent(QPaintEvent *) { + void paintEvent(QPaintEvent *) override + { QPlatformNativeInterface *ni = QGuiApplication::platformNativeInterface(); - const HDC hdc = (HDC)ni->nativeResourceForWindow(QByteArrayLiteral("getDC"), windowHandle()); + const auto hdc = reinterpret_cast<HDC>(ni->nativeResourceForWindow(QByteArrayLiteral("getDC"), windowHandle())); if (hdc) { const HBRUSH brush = CreateSolidBrush(RGB(255, 0, 0)); SelectObject(hdc, brush); @@ -8588,9 +8597,7 @@ public: } } - QSize sizeHint() const { - return QSize(400, 300); - } + QSize sizeHint() const override { return {400, 300}; }; private slots: void slotTimer() { @@ -8617,6 +8624,7 @@ void tst_QWidget::gdiPainting() void tst_QWidget::paintOnScreenPossible() { QWidget w1; + w1.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w1.setAttribute(Qt::WA_PaintOnScreen); QVERIFY(!w1.testAttribute(Qt::WA_PaintOnScreen)); @@ -8673,7 +8681,7 @@ void tst_QWidget::reparentStaticWidget() window2.resize(window2.size() + QSize(2, 2)); QTest::qWait(20); - child->setParent(0); + child->setParent(nullptr); child->show(); QTest::qWait(20); @@ -8743,12 +8751,13 @@ void tst_QWidget::QTBUG6883_reparentStaticWidget2() class ColorRedWidget : public QWidget { public: - ColorRedWidget(QWidget *parent = 0) + explicit ColorRedWidget(QWidget *parent = nullptr) : QWidget(parent, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::ToolTip) { } - void paintEvent(QPaintEvent *) { + void paintEvent(QPaintEvent *) override + { QPainter p(this); p.fillRect(rect(),Qt::red); } @@ -8759,6 +8768,7 @@ void tst_QWidget::translucentWidget() QPixmap pm(16,16); pm.fill(Qt::red); ColorRedWidget label; + label.setWindowTitle(QLatin1String(QTest::currentTestFunction())); label.setFixedSize(16,16); label.setAttribute(Qt::WA_TranslucentBackground); const QPoint labelPos = QGuiApplication::primaryScreen()->availableGeometry().topLeft(); @@ -8787,12 +8797,13 @@ class MaskResizeTestWidget : public QWidget { Q_OBJECT public: - MaskResizeTestWidget(QWidget* p =0) - : QWidget(p) { + explicit MaskResizeTestWidget(QWidget* p = nullptr) : QWidget(p) + { setMask(QRegion(QRect(0, 0, 100, 100).normalized())); } - void paintEvent(QPaintEvent* event) { + void paintEvent(QPaintEvent* event) override + { QPainter p(this); paintedRegion += event->region(); @@ -8818,10 +8829,11 @@ public slots: void tst_QWidget::setClearAndResizeMask() { UpdateWidget topLevel; + topLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); topLevel.resize(160, 160); centerOnScreen(&topLevel); topLevel.show(); - qApp->setActiveWindow(&topLevel); + QApplication::setActiveWindow(&topLevel); QVERIFY(QTest::qWaitForWindowExposed(&topLevel)); QTRY_VERIFY(topLevel.numPaintEvents > 0); topLevel.reset(); @@ -8968,6 +8980,7 @@ void tst_QWidget::setClearAndResizeMask() void tst_QWidget::maskedUpdate() { UpdateWidget topLevel; + topLevel.setWindowTitle(QLatin1String(QTest::currentTestFunction())); topLevel.resize(200, 200); centerOnScreen(&topLevel); const QRegion topLevelMask(50, 50, 70, 70); @@ -9121,16 +9134,17 @@ void tst_QWidget::syntheticEnterLeave() class MyWidget : public QWidget { public: - MyWidget(QWidget *parent = 0) : QWidget(parent), numEnterEvents(0), numLeaveEvents(0) {} - void enterEvent(QEvent *) { ++numEnterEvents; } - void leaveEvent(QEvent *) { ++numLeaveEvents; } - int numEnterEvents; - int numLeaveEvents; + using QWidget::QWidget; + void enterEvent(QEvent *) override { ++numEnterEvents; } + void leaveEvent(QEvent *) override { ++numLeaveEvents; } + int numEnterEvents = 0; + int numLeaveEvents = 0; }; QCursor::setPos(m_safeCursorPos); MyWidget window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.setWindowFlags(Qt::WindowStaysOnTopHint); window.move(200, 200); window.resize(200, 200); @@ -9226,31 +9240,32 @@ void tst_QWidget::taskQTBUG_4055_sendSyntheticEnterLeave() class SELParent : public QWidget { public: - SELParent(QWidget *parent = 0): QWidget(parent) { } + using QWidget::QWidget; - void mousePressEvent(QMouseEvent *) { child->show(); } - QWidget *child; + void mousePressEvent(QMouseEvent *) override { child->show(); } + QWidget *child = nullptr; }; class SELChild : public QWidget - { - public: - SELChild(QWidget *parent = 0) : QWidget(parent), numEnterEvents(0), numMouseMoveEvents(0) {} - void enterEvent(QEvent *) { ++numEnterEvents; } - void mouseMoveEvent(QMouseEvent *event) - { - QCOMPARE(event->button(), Qt::NoButton); - QCOMPARE(event->buttons(), QApplication::mouseButtons()); - QCOMPARE(event->modifiers(), QApplication::keyboardModifiers()); - ++numMouseMoveEvents; - } - void reset() { numEnterEvents = numMouseMoveEvents = 0; } - int numEnterEvents, numMouseMoveEvents; - }; + { + public: + using QWidget::QWidget; + void enterEvent(QEvent *) override { ++numEnterEvents; } + void mouseMoveEvent(QMouseEvent *event) override + { + QCOMPARE(event->button(), Qt::NoButton); + QCOMPARE(event->buttons(), QApplication::mouseButtons()); + QCOMPARE(event->modifiers(), QApplication::keyboardModifiers()); + ++numMouseMoveEvents; + } + void reset() { numEnterEvents = numMouseMoveEvents = 0; } + int numEnterEvents = 0, numMouseMoveEvents = 0; + }; QCursor::setPos(m_safeCursorPos); SELParent parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.move(200, 200); parent.resize(200, 200); SELChild child(&parent); @@ -9350,9 +9365,9 @@ class MyEvilObject : public QObject { Q_OBJECT public: - MyEvilObject(QWidget *widgetToCrash) : QObject(), widget(widgetToCrash) + explicit MyEvilObject(QWidget *widgetToCrash) : QObject(), widget(widgetToCrash) { - connect(widget, SIGNAL(destroyed(QObject*)), this, SLOT(beEvil(QObject*))); + connect(widget, &QObject::destroyed, this, &MyEvilObject::beEvil); delete widget; } QWidget *widget; @@ -9364,6 +9379,7 @@ private slots: void tst_QWidget::updateOnDestroyedSignal() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget *child = new QWidget(&widget); child->resize(m_testWidgetSize); @@ -9381,18 +9397,20 @@ void tst_QWidget::updateOnDestroyedSignal() void tst_QWidget::toplevelLineEditFocus() { QLineEdit w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setMinimumWidth(m_testWidgetSize.width()); w.show(); QVERIFY(QTest::qWaitForWindowExposed(&w)); - QTRY_COMPARE(QApplication::activeWindow(), (QWidget*)&w); - QTRY_COMPARE(QApplication::focusWidget(), (QWidget*)&w); + QTRY_COMPARE(QApplication::activeWindow(), static_cast<const QWidget *>(&w)); + QTRY_COMPARE(QApplication::focusWidget(), static_cast<const QWidget *>(&w)); } void tst_QWidget::focusWidget_task254563() { //having different visibility for widget is important QWidget top; + top.setWindowTitle(QLatin1String(QTest::currentTestFunction())); top.show(); QWidget container(&top); QWidget *widget = new QWidget(&container); @@ -9409,6 +9427,7 @@ void tst_QWidget::focusWidget_task254563() void tst_QWidget::destroyBackingStore() { UpdateWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); centerOnScreen(&w); w.reset(); w.show(); @@ -9435,7 +9454,7 @@ void tst_QWidget::destroyBackingStore() // Helper function QWidgetBackingStore* backingStore(QWidget &widget) { - QWidgetBackingStore *backingStore = 0; + QWidgetBackingStore *backingStore = nullptr; #ifdef QT_BUILD_INTERNAL if (QTLWExtra *topExtra = qt_widget_private(&widget)->maybeTopData()) backingStore = topExtra->backingStoreTracker.data(); @@ -9449,7 +9468,8 @@ void tst_QWidget::rectOutsideCoordinatesLimit_task144779() #ifndef QT_NO_CURSOR QGuiApplication::setOverrideCursor(Qt::BlankCursor); //keep the cursor out of screen grabs #endif - QWidget main(0,Qt::FramelessWindowHint); //don't get confused by the size of the window frame + QWidget main(nullptr, Qt::FramelessWindowHint); //don't get confused by the size of the window frame + main.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QPalette palette; palette.setColor(QPalette::Window, Qt::red); main.setPalette(palette); @@ -9492,6 +9512,7 @@ void tst_QWidget::setGraphicsEffect() { // Check that we don't have any effect by default. QScopedPointer<QWidget> widget(new QWidget); + widget->setWindowTitle(QLatin1String(QTest::currentTestFunction())); QVERIFY(!widget->graphicsEffect()); // SetGet check. @@ -9528,7 +9549,7 @@ void tst_QWidget::setGraphicsEffect() // Ensure the existing effect is uninstalled and deleted when setting a null effect blurEffect = new QGraphicsBlurEffect; widget->setGraphicsEffect(blurEffect); - widget->setGraphicsEffect(0); + widget->setGraphicsEffect(nullptr); QVERIFY(!widget->graphicsEffect()); QVERIFY(!blurEffect); } @@ -9542,6 +9563,7 @@ void tst_QWidget::activateWindow() // Create first mainwindow and set it active QScopedPointer<QMainWindow> mainwindow(new QMainWindow); + mainwindow->setWindowTitle(QLatin1String(QTest::currentTestFunction())); QLabel* label = new QLabel(mainwindow.data()); label->setMinimumWidth(m_testWidgetSize.width()); mainwindow->setWindowTitle(QStringLiteral("#1 ") + __FUNCTION__); @@ -9561,7 +9583,7 @@ void tst_QWidget::activateWindow() mainwindow2->move(mainwindow->geometry().bottomLeft() + QPoint(0, 50)); mainwindow2->setVisible(true); mainwindow2->activateWindow(); - qApp->processEvents(); + QCoreApplication::processEvents(); QTRY_VERIFY(!mainwindow->isActiveWindow()); QTRY_VERIFY(mainwindow2->isActiveWindow()); @@ -9569,7 +9591,7 @@ void tst_QWidget::activateWindow() // Revert first mainwindow back to visible active mainwindow->setVisible(true); mainwindow->activateWindow(); - qApp->processEvents(); + QCoreApplication::processEvents(); QTRY_VERIFY(mainwindow->isActiveWindow()); if (m_platform == QStringLiteral("winrt")) @@ -9605,7 +9627,8 @@ void tst_QWidget::focusProxyAndInputMethods() { if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::WindowActivation)) QSKIP("Window activation is not supported."); - QScopedPointer<QWidget> toplevel(new QWidget(0, Qt::X11BypassWindowManagerHint)); + QScopedPointer<QWidget> toplevel(new QWidget(nullptr, Qt::X11BypassWindowManagerHint)); + toplevel->setWindowTitle(QLatin1String(QTest::currentTestFunction())); toplevel->resize(200, 200); toplevel->setAttribute(Qt::WA_InputMethodEnabled, true); @@ -9652,6 +9675,7 @@ public: void tst_QWidget::scrollWithoutBackingStore() { scrollWidgetWBS scrollable; + scrollable.setWindowTitle(QLatin1String(QTest::currentTestFunction())); scrollable.resize(200, 200); QLabel child(QString("@"),&scrollable); child.resize(50,50); @@ -9670,6 +9694,7 @@ void tst_QWidget::scrollWithoutBackingStore() void tst_QWidget::taskQTBUG_7532_tabOrderWithFocusProxy() { QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setFocusPolicy(Qt::TabFocus); QWidget *fp = new QWidget(&w); fp->setFocusPolicy(Qt::TabFocus); @@ -9682,7 +9707,8 @@ void tst_QWidget::taskQTBUG_7532_tabOrderWithFocusProxy() void tst_QWidget::movedAndResizedAttributes() { // Use Qt::Tool as fully decorated windows have a minimum width of 160 on - QWidget w(0, Qt::Tool); + QWidget w(nullptr, Qt::Tool); + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.show(); QVERIFY(!w.testAttribute(Qt::WA_Moved)); @@ -9730,7 +9756,8 @@ void tst_QWidget::movedAndResizedAttributes() void tst_QWidget::childAt() { - QWidget parent(0, Qt::FramelessWindowHint); + QWidget parent(nullptr, Qt::FramelessWindowHint); + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.resize(200, 200); QWidget *child = new QWidget(&parent); @@ -9810,6 +9837,7 @@ void tst_QWidget::taskQTBUG_11373() void tst_QWidget::taskQTBUG_17333_ResizeInfiniteRecursion() { QTableView tb; + tb.setWindowTitle(QLatin1String(QTest::currentTestFunction())); const char *s = "border: 1px solid;"; tb.setStyleSheet(s); tb.show(); @@ -9822,6 +9850,7 @@ void tst_QWidget::taskQTBUG_17333_ResizeInfiniteRecursion() void tst_QWidget::nativeChildFocus() { QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setMinimumWidth(m_testWidgetSize.width()); w.setWindowTitle(__FUNCTION__); QLayout *layout = new QVBoxLayout; @@ -9859,8 +9888,8 @@ static bool lenientCompare(const QPixmap &actual, const QPixmap &expected) const int size = actual.width() * actual.height(); const int threshold = QPixmap::defaultDepth() == 16 ? 10 : 2; - QRgb *a = (QRgb *)actualImage.bits(); - QRgb *e = (QRgb *)expectedImage.bits(); + auto a = reinterpret_cast<const QRgb *>(actualImage.bits()); + auto e = reinterpret_cast<const QRgb *>(expectedImage.bits()); for (int i = 0; i < size; ++i) { const QColor ca(a[i]); const QColor ce(e[i]); @@ -9880,6 +9909,7 @@ void tst_QWidget::grab() { for (int opaque = 0; opaque < 2; ++opaque) { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QImage image(128, 128, opaque ? QImage::Format_RGB32 : QImage::Format_ARGB32_Premultiplied); for (int row = 0; row < image.height(); ++row) { QRgb *line = reinterpret_cast<QRgb *>(image.scanLine(row)); @@ -9929,12 +9959,13 @@ static inline QString mouseEventLogEntry(const QString &objectName, QEvent::Type return result; } -class GrabLoggerWidget : public QWidget { +class GrabLoggerWidget : public QWidget +{ public: - explicit GrabLoggerWidget(QStringList *log, QWidget *parent = 0) : QWidget(parent), m_log(log) {} + explicit GrabLoggerWidget(QStringList *log, QWidget *parent = nullptr) : QWidget(parent), m_log(log) {} protected: - bool event(QEvent *e) + bool event(QEvent *e) override { switch (e->type()) { case QEvent::MouseButtonPress: @@ -9958,6 +9989,7 @@ void tst_QWidget::grabMouse() { QStringList log; GrabLoggerWidget w(&log); + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setObjectName(QLatin1String("tst_qwidget_grabMouse")); w.setWindowTitle(w.objectName()); QLayout *layout = new QVBoxLayout(&w); @@ -9969,7 +10001,7 @@ void tst_QWidget::grabMouse() layout->addWidget(grabber); centerOnScreen(&w); w.show(); - qApp->setActiveWindow(&w); + QApplication::setActiveWindow(&w); QVERIFY(QTest::qWaitForWindowActive(&w)); QStringList expectedLog; @@ -9978,7 +10010,7 @@ void tst_QWidget::grabMouse() grabber->grabMouse(); const int step = w.height() / 5; for ( ; mousePos.y() < w.height() ; mousePos.ry() += step) { - QTest::mouseClick(w.windowHandle(), Qt::LeftButton, 0, mousePos); + QTest::mouseClick(w.windowHandle(), Qt::LeftButton, Qt::KeyboardModifiers(), mousePos); // Events should go to the grabber child using its coordinates. const QPoint expectedPos = grabber->mapFromParent(mousePos); expectedLog.push_back(mouseEventLogEntry(grabberObjectName, QEvent::MouseButtonPress, expectedPos, Qt::LeftButton)); @@ -9991,6 +10023,7 @@ void tst_QWidget::grabMouse() void tst_QWidget::grabKeyboard() { QWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.setObjectName(QLatin1String("tst_qwidget_grabKeyboard")); w.setWindowTitle(w.objectName()); QLayout *layout = new QVBoxLayout(&w); @@ -10002,7 +10035,7 @@ void tst_QWidget::grabKeyboard() layout->addWidget(nonGrabber); centerOnScreen(&w); w.show(); - qApp->setActiveWindow(&w); + QApplication::setActiveWindow(&w); QVERIFY(QTest::qWaitForWindowActive(&w)); nonGrabber->setFocus(); grabber->grabKeyboard(); @@ -10014,16 +10047,7 @@ void tst_QWidget::grabKeyboard() class TouchMouseWidget : public QWidget { public: - explicit TouchMouseWidget(QWidget *parent = 0) - : QWidget(parent), - m_touchBeginCount(0), - m_touchUpdateCount(0), - m_touchEndCount(0), - m_touchEventCount(0), - m_gestureEventCount(0), - m_acceptTouch(false), - m_mouseEventCount(0), - m_acceptMouse(true) + explicit TouchMouseWidget(QWidget *parent = nullptr) : QWidget(parent) { resize(200, 200); } @@ -10040,7 +10064,7 @@ public: } protected: - bool event(QEvent *e) + bool event(QEvent *e) override { switch (e->type()) { case QEvent::TouchBegin: @@ -10079,14 +10103,14 @@ protected: } public: - int m_touchBeginCount; - int m_touchUpdateCount; - int m_touchEndCount; - int m_touchEventCount; - int m_gestureEventCount; - bool m_acceptTouch; - int m_mouseEventCount; - bool m_acceptMouse; + int m_touchBeginCount = 0; + int m_touchUpdateCount = 0; + int m_touchEndCount = 0; + int m_touchEventCount = 0; + int m_gestureEventCount = 0; + bool m_acceptTouch = false; + int m_mouseEventCount = 0; + bool m_acceptMouse = true; QPointF m_lastMouseEventPos; }; @@ -10095,6 +10119,7 @@ void tst_QWidget::touchEventSynthesizedMouseEvent() { // Simple case, we ignore the touch events, we get mouse events instead TouchMouseWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.show(); QVERIFY(QTest::qWaitForWindowExposed(widget.windowHandle())); QCOMPARE(widget.m_touchEventCount, 0); @@ -10117,6 +10142,7 @@ void tst_QWidget::touchEventSynthesizedMouseEvent() { // We accept the touch events, no mouse event is generated TouchMouseWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.setAcceptTouch(true); widget.show(); QVERIFY(QTest::qWaitForWindowExposed(widget.windowHandle())); @@ -10138,6 +10164,7 @@ void tst_QWidget::touchEventSynthesizedMouseEvent() // Parent accepts touch events, child ignore both mouse and touch // We should see propagation of the TouchBegin TouchMouseWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.setAcceptTouch(true); TouchMouseWidget child(&parent); child.move(5, 5); @@ -10160,6 +10187,7 @@ void tst_QWidget::touchEventSynthesizedMouseEvent() // Parent accepts mouse events, child ignore both mouse and touch // We should see propagation of the TouchBegin into a MouseButtonPress TouchMouseWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); TouchMouseWidget child(&parent); const QPoint childPos(5, 5); child.move(childPos); @@ -10185,6 +10213,7 @@ void tst_QWidget::touchEventSynthesizedMouseEvent() void tst_QWidget::touchUpdateOnNewTouch() { TouchMouseWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.setAcceptTouch(true); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(new QWidget); @@ -10221,6 +10250,7 @@ void tst_QWidget::touchUpdateOnNewTouch() void tst_QWidget::touchEventsForGesturePendingWidgets() { TouchMouseWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); TouchMouseWidget child(&parent); parent.grabGesture(Qt::TapAndHoldGesture); parent.show(); @@ -10259,8 +10289,9 @@ void tst_QWidget::touchEventsForGesturePendingWidgets() void tst_QWidget::styleSheetPropagation() { QTableView tw; + tw.setWindowTitle(QLatin1String(QTest::currentTestFunction())); tw.setStyleSheet("background-color: red;"); - foreach (QObject *child, tw.children()) { + for (QObject *child : tw.children()) { if (QWidget *w = qobject_cast<QWidget *>(child)) QCOMPARE(w->style(), tw.style()); } @@ -10270,7 +10301,7 @@ class DestroyTester : public QObject { Q_OBJECT public: - DestroyTester(QObject *parent) : QObject(parent) { parentDestroyed = 0; } + explicit DestroyTester(QObject *parent = nullptr) : QObject(parent) { parentDestroyed = 0; } static int parentDestroyed; public slots: void parentDestroyedSlot() { @@ -10285,7 +10316,7 @@ void tst_QWidget::destroyedSignal() { QWidget *w = new QWidget; DestroyTester *t = new DestroyTester(w); - connect(w, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + connect(w, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); QCOMPARE(DestroyTester::parentDestroyed, 0); delete w; QCOMPARE(DestroyTester::parentDestroyed, 1); @@ -10294,7 +10325,7 @@ void tst_QWidget::destroyedSignal() { QWidget *w = new QWidget; DestroyTester *t = new DestroyTester(w); - connect(w, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + connect(w, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); w->blockSignals(true); QCOMPARE(DestroyTester::parentDestroyed, 0); delete w; @@ -10304,7 +10335,7 @@ void tst_QWidget::destroyedSignal() { QObject *o = new QWidget; DestroyTester *t = new DestroyTester(o); - connect(o, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + connect(o, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); QCOMPARE(DestroyTester::parentDestroyed, 0); delete o; QCOMPARE(DestroyTester::parentDestroyed, 1); @@ -10312,8 +10343,8 @@ void tst_QWidget::destroyedSignal() { QObject *o = new QWidget; - DestroyTester *t = new DestroyTester(o); - connect(o, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + auto t = new DestroyTester; + connect(o, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); o->blockSignals(true); QCOMPARE(DestroyTester::parentDestroyed, 0); delete o; @@ -10322,8 +10353,8 @@ void tst_QWidget::destroyedSignal() { QWidget *w = new QWidget; - DestroyTester *t = new DestroyTester(0); - connect(w, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + auto t = new DestroyTester; + connect(w, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); QCOMPARE(DestroyTester::parentDestroyed, 0); delete w; QCOMPARE(DestroyTester::parentDestroyed, 1); @@ -10332,8 +10363,8 @@ void tst_QWidget::destroyedSignal() { QWidget *w = new QWidget; - DestroyTester *t = new DestroyTester(0); - connect(w, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + auto t = new DestroyTester; + connect(w, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); w->blockSignals(true); QCOMPARE(DestroyTester::parentDestroyed, 0); delete w; @@ -10343,8 +10374,8 @@ void tst_QWidget::destroyedSignal() { QObject *o = new QWidget; - DestroyTester *t = new DestroyTester(0); - connect(o, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + auto t = new DestroyTester; + connect(o, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); QCOMPARE(DestroyTester::parentDestroyed, 0); delete o; QCOMPARE(DestroyTester::parentDestroyed, 1); @@ -10353,8 +10384,8 @@ void tst_QWidget::destroyedSignal() { QObject *o = new QWidget; - DestroyTester *t = new DestroyTester(0); - connect(o, SIGNAL(destroyed()), t, SLOT(parentDestroyedSlot())); + auto t = new DestroyTester; + connect(o, &QObject::destroyed, t, &DestroyTester::parentDestroyedSlot); o->blockSignals(true); QCOMPARE(DestroyTester::parentDestroyed, 0); delete o; @@ -10370,10 +10401,11 @@ void tst_QWidget::underMouse() // Move the mouse cursor to a safe location QCursor::setPos(m_safeCursorPos); - ColorWidget topLevelWidget(0, Qt::FramelessWindowHint, Qt::blue); + ColorWidget topLevelWidget(nullptr, Qt::FramelessWindowHint, Qt::blue); + topLevelWidget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); ColorWidget childWidget1(&topLevelWidget, Qt::Widget, Qt::yellow); ColorWidget childWidget2(&topLevelWidget, Qt::Widget, Qt::black); - ColorWidget popupWidget(0, Qt::Popup, Qt::green); + ColorWidget popupWidget(nullptr, Qt::Popup, Qt::green); topLevelWidget.setObjectName("topLevelWidget"); childWidget1.setObjectName("childWidget1"); @@ -10562,7 +10594,7 @@ class EnterTestModalDialog : public QDialog { Q_OBJECT public: - EnterTestModalDialog() : QDialog(), button(0) + EnterTestModalDialog() { setGeometry(100, 300, 150, 100); button = new QPushButton(this); @@ -10576,7 +10608,6 @@ class EnterTestMainDialog : public QDialog { Q_OBJECT public: - EnterTestMainDialog() : QDialog(), modal(0), enters(0) {} public slots: void buttonPressed() @@ -10604,7 +10635,7 @@ public slots: modal->close(); } - bool eventFilter(QObject *o, QEvent *e) + bool eventFilter(QObject *o, QEvent *e) override { switch (e->type()) { case QEvent::Enter: @@ -10618,8 +10649,8 @@ public slots: } public: - EnterTestModalDialog *modal; - int enters; + EnterTestModalDialog *modal = nullptr; + int enters = 0; }; // A modal dialog launched by clicking a button should not trigger excess enter events @@ -10633,9 +10664,10 @@ void tst_QWidget::taskQTBUG_27643_enterEvents() QCursor::setPos(m_safeCursorPos); EnterTestMainDialog dialog; + dialog.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QPushButton button(&dialog); - connect(&button, SIGNAL(clicked()), &dialog, SLOT(buttonPressed())); + connect(&button, &QAbstractButton::clicked, &dialog, &EnterTestMainDialog::buttonPressed); dialog.setGeometry(100, 100, 150, 100); button.setGeometry(10, 10, 100, 50); @@ -10647,7 +10679,7 @@ void tst_QWidget::taskQTBUG_27643_enterEvents() QWindowSystemInterface::handleEnterEvent(window, overButton, window->mapToGlobal(overButton)); QTest::mouseMove(window, overButton); - QTest::mouseClick(window, Qt::LeftButton, 0, overButton, 0); + QTest::mouseClick(window, Qt::LeftButton, Qt::KeyboardModifiers(), overButton, 0); // Modal dialog opened in EnterTestMainDialog::buttonPressed()... @@ -10659,20 +10691,22 @@ void tst_QWidget::taskQTBUG_27643_enterEvents() class KeyboardWidget : public QWidget { public: - KeyboardWidget(QWidget* parent = 0) : QWidget(parent), m_eventCounter(0) {} - virtual void mousePressEvent(QMouseEvent* ev) override { + using QWidget::QWidget; + void mousePressEvent(QMouseEvent* ev) override + { m_modifiers = ev->modifiers(); m_appModifiers = QApplication::keyboardModifiers(); ++m_eventCounter; } Qt::KeyboardModifiers m_modifiers; Qt::KeyboardModifiers m_appModifiers; - int m_eventCounter; + int m_eventCounter = 0; }; void tst_QWidget::keyboardModifiers() { KeyboardWidget w; + w.setWindowTitle(QLatin1String(QTest::currentTestFunction())); w.resize(300, 300); w.show(); QVERIFY(QTest::qWaitForWindowExposed(&w)); @@ -10685,17 +10719,17 @@ void tst_QWidget::keyboardModifiers() class DClickWidget : public QWidget { public: - DClickWidget() : triggered(false) {} - void mouseDoubleClickEvent(QMouseEvent *) + void mouseDoubleClickEvent(QMouseEvent *) override { triggered = true; } - bool triggered; + bool triggered = false; }; void tst_QWidget::mouseDoubleClickBubbling_QTBUG29680() { DClickWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget child(&parent); parent.resize(200, 200); child.resize(200, 200); @@ -10710,6 +10744,7 @@ void tst_QWidget::mouseDoubleClickBubbling_QTBUG29680() void tst_QWidget::largerThanScreen_QTBUG30142() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(200, 4000); widget.show(); QVERIFY(QTest::qWaitForWindowExposed(&widget)); @@ -10727,6 +10762,7 @@ void tst_QWidget::largerThanScreen_QTBUG30142() void tst_QWidget::resizeStaticContentsChildWidget_QTBUG35282() { QWidget widget; + widget.setWindowTitle(QLatin1String(QTest::currentTestFunction())); widget.resize(200,200); UpdateWidget childWidget(&widget); @@ -10752,11 +10788,12 @@ void tst_QWidget::qmlSetParentHelper() { #ifdef QT_BUILD_INTERNAL QWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget child; QVERIFY(QAbstractDeclarativeData::setWidgetParent); QAbstractDeclarativeData::setWidgetParent(&child, &parent); QCOMPARE(child.parentWidget(), &parent); - QAbstractDeclarativeData::setWidgetParent(&child, 0); + QAbstractDeclarativeData::setWidgetParent(&child, nullptr); QVERIFY(!child.parentWidget()); #else QSKIP("Needs QT_BUILD_INTERNAL"); @@ -10870,6 +10907,7 @@ protected: void tst_QWidget::tabletTracking() { QWidget parent; + parent.setWindowTitle(QLatin1String(QTest::currentTestFunction())); parent.resize(200,200); // QWidgetWindow::handleTabletEvent doesn't deliver tablet events to the window's widget, only to a child. // So it doesn't do any good to show a TabletWidget directly: it needs a parent. @@ -10888,7 +10926,7 @@ void tst_QWidget::tabletTracking() QPointF deviceGlobal = QHighDpi::toNativePixels(global, window->screen()); qint64 uid = 1234UL; - QWindowSystemInterface::handleTabletEvent(window, QDateTime::currentMSecsSinceEpoch(), deviceLocal, deviceGlobal, + QWindowSystemInterface::handleTabletEvent(window, ulong(QDateTime::currentMSecsSinceEpoch()), deviceLocal, deviceGlobal, QTabletEvent::Stylus, QTabletEvent::Pen, Qt::NoButton, 0, 0, 0, 0, 0, 0, uid, Qt::NoModifier); QCoreApplication::processEvents(); QTRY_COMPARE(widget.moveEventCount, 1); @@ -10897,7 +10935,7 @@ void tst_QWidget::tabletTracking() local += QPoint(10, 10); deviceLocal += QPoint(10, 10); deviceGlobal += QPoint(10, 10); - QWindowSystemInterface::handleTabletEvent(window, QDateTime::currentMSecsSinceEpoch(), deviceLocal, deviceGlobal, + QWindowSystemInterface::handleTabletEvent(window, ulong(QDateTime::currentMSecsSinceEpoch()), deviceLocal, deviceGlobal, QTabletEvent::Stylus, QTabletEvent::Pen, Qt::NoButton, 0, 0, 0, 0, 0, 0, uid, Qt::NoModifier); QCoreApplication::processEvents(); QTRY_COMPARE(widget.moveEventCount, 2); @@ -10906,7 +10944,7 @@ void tst_QWidget::tabletTracking() QCoreApplication::processEvents(); QTRY_COMPARE(widget.trackingChangeEventCount, 2); - QWindowSystemInterface::handleTabletEvent(window, QDateTime::currentMSecsSinceEpoch(), deviceLocal, deviceGlobal, + QWindowSystemInterface::handleTabletEvent(window, ulong(QDateTime::currentMSecsSinceEpoch()), deviceLocal, deviceGlobal, QTabletEvent::Stylus, QTabletEvent::Pen, Qt::LeftButton, 0, 0, 0, 0, 0, 0, uid, Qt::NoModifier); QCoreApplication::processEvents(); QTRY_COMPARE(widget.pressEventCount, 1); @@ -10914,12 +10952,12 @@ void tst_QWidget::tabletTracking() local += QPoint(10, 10); deviceLocal += QPoint(10, 10); deviceGlobal += QPoint(10, 10); - QWindowSystemInterface::handleTabletEvent(window, QDateTime::currentMSecsSinceEpoch(), deviceLocal, deviceGlobal, + QWindowSystemInterface::handleTabletEvent(window, ulong(QDateTime::currentMSecsSinceEpoch()), deviceLocal, deviceGlobal, QTabletEvent::Stylus, QTabletEvent::Pen, Qt::LeftButton, 0, 0, 0, 0, 0, 0, uid, Qt::NoModifier); QCoreApplication::processEvents(); QTRY_COMPARE(widget.moveEventCount, 3); - QWindowSystemInterface::handleTabletEvent(window, QDateTime::currentMSecsSinceEpoch(), deviceLocal, deviceGlobal, + QWindowSystemInterface::handleTabletEvent(window, ulong(QDateTime::currentMSecsSinceEpoch()), deviceLocal, deviceGlobal, QTabletEvent::Stylus, QTabletEvent::Pen, Qt::NoButton, 0, 0, 0, 0, 0, 0, uid, Qt::NoModifier); QCoreApplication::processEvents(); QTRY_COMPARE(widget.releaseEventCount, 1); @@ -10927,7 +10965,7 @@ void tst_QWidget::tabletTracking() local += QPoint(10, 10); deviceLocal += QPoint(10, 10); deviceGlobal += QPoint(10, 10); - QWindowSystemInterface::handleTabletEvent(window, QDateTime::currentMSecsSinceEpoch(), deviceLocal, deviceGlobal, + QWindowSystemInterface::handleTabletEvent(window, ulong(QDateTime::currentMSecsSinceEpoch()), deviceLocal, deviceGlobal, QTabletEvent::Stylus, QTabletEvent::Pen, Qt::NoButton, 0, 0, 0, 0, 0, 0, uid, Qt::NoModifier); QCoreApplication::processEvents(); QTRY_COMPARE(widget.moveEventCount, 3); diff --git a/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp b/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp index 8b558aa56f..c6b5669965 100644 --- a/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp +++ b/tests/auto/widgets/kernel/qwidget_window/tst_qwidget_window.cpp @@ -54,12 +54,25 @@ using namespace QTestPrivate; +// Compare a window position that may go through scaling in the platform plugin with fuzz. +static inline bool qFuzzyCompareWindowPosition(const QPoint &p1, const QPoint p2, int fuzz) +{ + return (p1 - p2).manhattanLength() <= fuzz; +} + +static QString msgPointMismatch(const QPoint &p1, const QPoint p2) +{ + QString result; + QDebug(&result) << p1 << "!=" << p2 << ", manhattanLength=" << (p1 - p2).manhattanLength(); + return result; +} + class tst_QWidget_window : public QObject { Q_OBJECT public: - tst_QWidget_window(){}; + tst_QWidget_window(); public slots: void initTestCase(); @@ -110,8 +123,20 @@ private slots: void nativeShow(); void QTBUG_56277_resize_on_showEvent(); + +private: + QSize m_testWidgetSize; + const int m_fuzz; }; +tst_QWidget_window::tst_QWidget_window() : + m_fuzz(int(QHighDpiScaling::factor(QGuiApplication::primaryScreen()))) +{ + const int screenWidth = QGuiApplication::primaryScreen()->geometry().width(); + const int width = qMax(200, 100 * ((screenWidth + 500) / 1000)); + m_testWidgetSize = QSize(width, width); +} + void tst_QWidget_window::initTestCase() { } @@ -162,65 +187,65 @@ void tst_QWidget_window::tst_min_max_size() void tst_QWidget_window::tst_move_show() { QWidget w; - w.move(100, 100); + const QPoint pos(100, 100); + w.move(pos); w.show(); #ifdef Q_OS_WINRT QEXPECT_FAIL("", "Winrt does not support move", Abort); #endif - QCOMPARE(w.pos(), QPoint(100, 100)); -// QCoreApplication::processEvents(QEventLoop::AllEvents, 3000); + QVERIFY2(qFuzzyCompareWindowPosition(w.pos(), pos, m_fuzz), + qPrintable(msgPointMismatch(w.pos(), pos))); } void tst_QWidget_window::tst_show_move() { QWidget w; w.show(); - w.move(100, 100); - QCOMPARE(w.pos(), QPoint(100, 100)); -// QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); + const QPoint pos(100, 100); + w.move(pos); + QVERIFY2(qFuzzyCompareWindowPosition(w.pos(), pos, m_fuzz), + qPrintable(msgPointMismatch(w.pos(), pos))); } void tst_QWidget_window::tst_show_move_hide_show() { QWidget w; w.show(); - w.move(100, 100); + const QPoint pos(100, 100); + w.move(pos); w.hide(); w.show(); - QCOMPARE(w.pos(), QPoint(100, 100)); -// QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); + QVERIFY2(qFuzzyCompareWindowPosition(w.pos(), pos, m_fuzz), + qPrintable(msgPointMismatch(w.pos(), pos))); } void tst_QWidget_window::tst_resize_show() { QWidget w; - w.resize(200, 200); + w.resize(m_testWidgetSize); w.show(); #ifdef Q_OS_WINRT QEXPECT_FAIL("", "Winrt does not support resize", Abort); #endif - QCOMPARE(w.size(), QSize(200, 200)); -// QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); + QCOMPARE(w.size(), m_testWidgetSize); } void tst_QWidget_window::tst_show_resize() { QWidget w; w.show(); - w.resize(200, 200); - QCOMPARE(w.size(), QSize(200, 200)); -// QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); + w.resize(m_testWidgetSize); + QCOMPARE(w.size(), m_testWidgetSize); } void tst_QWidget_window::tst_show_resize_hide_show() { QWidget w; w.show(); - w.resize(200, 200); + w.resize(m_testWidgetSize); w.hide(); w.show(); - QCOMPARE(w.size(), QSize(200, 200)); -// QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); + QCOMPARE(w.size(), m_testWidgetSize); } class PaintTestWidget : public QWidget @@ -857,7 +882,7 @@ void tst_QWidget_window::tst_updateWinId_QTBUG40681() lbl->setAttribute(Qt::WA_NativeWindow); lbl->setObjectName("label1"); vl->addWidget(lbl); - w.setMinimumWidth(200); + w.setMinimumWidth(m_testWidgetSize.width()); w.show(); @@ -880,6 +905,7 @@ void tst_QWidget_window::tst_updateWinId_QTBUG40681() void tst_QWidget_window::tst_recreateWindow_QTBUG40817() { QTabWidget tab; + tab.setMinimumWidth(m_testWidgetSize.width()); QWidget *w = new QWidget; tab.addTab(w, "Tab1"); @@ -946,7 +972,7 @@ void tst_QWidget_window::tst_resize_count() resize.resizeCount = 0; ResizeWidget child(&resize); - child.resize(200,200); + child.resize(m_testWidgetSize); child.winId(); child.show(); QVERIFY(QTest::qWaitForWindowExposed(&child)); @@ -963,7 +989,7 @@ void tst_QWidget_window::tst_resize_count() { ResizeWidget parent; ResizeWidget child(&parent); - child.resize(200,200); + child.resize(m_testWidgetSize); child.winId(); parent.show(); QVERIFY(QTest::qWaitForWindowExposed(&parent)); @@ -1076,6 +1102,7 @@ void tst_QWidget_window::QTBUG_50561_QCocoaBackingStore_paintDevice_crash() ApplicationStateSaver as; QMainWindow w; + w.setMinimumWidth(m_testWidgetSize.width()); w.addToolBar(new QToolBar(&w)); w.show(); QVERIFY(QTest::qWaitForWindowExposed(&w)); diff --git a/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp b/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp index b101f47bcd..954ee6471d 100644 --- a/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp +++ b/tests/auto/widgets/widgets/qdoublespinbox/tst_qdoublespinbox.cpp @@ -324,7 +324,9 @@ void tst_QDoubleSpinBox::setPrefixSuffix() QFETCH(QString, expectedCleanText); QFETCH(bool, show); - QDoubleSpinBox spin(0); + QDoubleSpinBox spin; + if (show) + spin.show(); spin.setDecimals(decimals); const QSize size1 = spin.sizeHint(); spin.setPrefix(prefix); @@ -332,17 +334,17 @@ void tst_QDoubleSpinBox::setPrefixSuffix() spin.setSuffix(suffix); const QSize size3 = spin.sizeHint(); spin.setValue(value); - if (show) - spin.show(); QCOMPARE(spin.text(), expectedText); QCOMPARE(spin.cleanText(), expectedCleanText); - if (!prefix.isEmpty() && !suffix.isEmpty()) { - QVERIFY(size1.width() < size2.width()); + if (!suffix.isEmpty()) { QVERIFY(size2.width() < size3.width()); spin.setSuffix(QString()); QCOMPARE(spin.sizeHint(), size2); + } + if (!prefix.isEmpty()) { + QVERIFY(size1.width() < size2.width()); spin.setPrefix(QString()); QCOMPARE(spin.sizeHint(), size1); } diff --git a/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp b/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp index 8b2f032172..2b59a227b3 100644 --- a/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp +++ b/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2019 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. @@ -49,6 +49,8 @@ #include <QScreen> #include <QSizeGrip> +#include <QVector> + QT_BEGIN_NAMESPACE #if 1 // Used to be excluded in Qt4 for Q_WS_WIN extern bool qt_tab_all_widgets(); @@ -58,7 +60,7 @@ QT_END_NAMESPACE static inline bool tabAllWidgets() { #if !defined(Q_OS_WIN) - if (qApp->style()->inherits("QMacStyle")) + if (QApplication::style()->inherits("QMacStyle")) return qt_tab_all_widgets(); #endif return true; @@ -69,17 +71,17 @@ static inline void triggerSignal(QMdiSubWindow *window, QMdiArea *workspace, { if (signal == SIGNAL(windowMaximized())) { window->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); if (window->parent()) QVERIFY(window->isMaximized()); } else if (signal == SIGNAL(windowMinimized())) { window->showMinimized(); - qApp->processEvents(); + QCoreApplication::processEvents(); if (window->parent()) QVERIFY(window->isMinimized()); } else if (signal == SIGNAL(windowRestored())) { window->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); window->showNormal(); QTRY_VERIFY(!window->isMinimized()); QTRY_VERIFY(!window->isMaximized()); @@ -87,39 +89,39 @@ static inline void triggerSignal(QMdiSubWindow *window, QMdiArea *workspace, } else if (signal == SIGNAL(aboutToActivate())) { if (window->parent()) { workspace->setActiveSubWindow(window); - qApp->processEvents(); + QCoreApplication::processEvents(); } } else if (signal == SIGNAL(windowActivated())) { if (window->parent()) { workspace->setActiveSubWindow(window); - qApp->processEvents(); + QCoreApplication::processEvents(); } } else if (signal == SIGNAL(windowDeactivated())) { if (!window->parent()) return; workspace->setActiveSubWindow(window); - qApp->processEvents(); - workspace->setActiveSubWindow(0); - qApp->processEvents(); + QCoreApplication::processEvents(); + workspace->setActiveSubWindow(nullptr); + QCoreApplication::processEvents(); } } // --- from tst_qgraphicsview.cpp --- static void sendMousePress(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::LeftButton) { - QMouseEvent event(QEvent::MouseButtonPress, point, widget->mapToGlobal(point), button, 0, 0); + QMouseEvent event(QEvent::MouseButtonPress, point, widget->mapToGlobal(point), button, {}, {}); QApplication::sendEvent(widget, &event); } static void sendMouseMove(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::LeftButton) { - QMouseEvent event(QEvent::MouseMove, point, widget->mapToGlobal(point), button, button, 0); + QMouseEvent event(QEvent::MouseMove, point, widget->mapToGlobal(point), button, button, {}); QApplication::sendEvent(widget, &event); } static void sendMouseRelease(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::LeftButton) { - QMouseEvent event(QEvent::MouseButtonRelease, point, widget->mapToGlobal(point), button, 0, 0); + QMouseEvent event(QEvent::MouseButtonRelease, point, widget->mapToGlobal(point), button, {}, {}); QApplication::sendEvent(widget, &event); } // --- @@ -128,7 +130,7 @@ static void sendMouseDoubleClick(QWidget *widget, const QPoint &point, Qt::Mouse { sendMousePress(widget, point, button); sendMouseRelease(widget, point, button); - QMouseEvent event(QEvent::MouseButtonDblClick, point, widget->mapToGlobal(point), button, 0, 0); + QMouseEvent event(QEvent::MouseButtonDblClick, point, widget->mapToGlobal(point), button, {}, {}); QApplication::sendEvent(widget, &event); } @@ -137,6 +139,15 @@ static const Qt::WindowFlags StandardWindowFlags static const Qt::WindowFlags DialogWindowFlags = Qt::WindowTitleHint | Qt::WindowSystemMenuHint; +class LayoutDirectionGuard +{ +public: + Q_DISABLE_COPY(LayoutDirectionGuard); + + LayoutDirectionGuard() = default; + ~LayoutDirectionGuard() { QApplication::setLayoutDirection(Qt::LeftToRight); } +}; + Q_DECLARE_METATYPE(Qt::WindowState); Q_DECLARE_METATYPE(Qt::WindowStates); Q_DECLARE_METATYPE(Qt::WindowType); @@ -148,6 +159,7 @@ class tst_QMdiSubWindow : public QObject Q_OBJECT private slots: void initTestCase(); + void cleanup(); void sizeHint(); void minimumSizeHint(); void minimumSize(); @@ -202,6 +214,14 @@ private slots: void tst_QMdiSubWindow::initTestCase() { qRegisterMetaType<Qt::WindowStates>("Qt::WindowStates"); + // Avoid unnecessary waits for empty top level widget lists when + // testing menus. + QApplication::setEffectEnabled(Qt::UI_AnimateMenu, false); +} + +void tst_QMdiSubWindow::cleanup() +{ + QVERIFY(QApplication::topLevelWidgets().isEmpty()); } void tst_QMdiSubWindow::sizeHint() @@ -211,34 +231,38 @@ void tst_QMdiSubWindow::sizeHint() window->show(); QCOMPARE(window->sizeHint(), window->minimumSizeHint()); QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction())); workspace.addSubWindow(window); QCOMPARE(window->sizeHint(), window->minimumSizeHint()); } void tst_QMdiSubWindow::minimumSizeHint() { + const auto globalStrut = QApplication::globalStrut(); QMdiSubWindow window; + window.setWindowTitle(QLatin1String(QTest::currentTestFunction())); window.show(); - QCOMPARE(window.minimumSizeHint(), qApp->globalStrut()); + QCOMPARE(window.minimumSizeHint(), globalStrut); window.setWidget(new QWidget); QCOMPARE(window.minimumSizeHint(), window.layout()->minimumSize() - .expandedTo(qApp->globalStrut())); + .expandedTo(globalStrut)); delete window.widget(); delete window.layout(); window.setWidget(new QWidget); - QCOMPARE(window.minimumSizeHint(), qApp->globalStrut()); + QCOMPARE(window.minimumSizeHint(), globalStrut); window.widget()->show(); QCOMPARE(window.minimumSizeHint(), window.widget()->minimumSizeHint() - .expandedTo(qApp->globalStrut())); + .expandedTo(globalStrut)); } void tst_QMdiSubWindow::minimumSize() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.resize(200, 200); // Check that we respect the minimum size set on the sub-window itself. @@ -278,7 +302,7 @@ void tst_QMdiSubWindow::setWidget() QCOMPARE(window.widget(), static_cast<QWidget *>(widget)); QCOMPARE(widget->parentWidget(), static_cast<QWidget *>(&window)); - window.setWidget(0); + window.setWidget(nullptr); QVERIFY(widget); QVERIFY(!widget->parent()); QVERIFY(!window.widget()); @@ -308,12 +332,13 @@ void tst_QMdiSubWindow::setWindowState() { QFETCH(Qt::WindowState, windowState); QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *window = qobject_cast<QMdiSubWindow *>(workspace.addSubWindow(new QLineEdit)); window->show(); workspace.show(); QVERIFY(QTest::qWaitForWindowExposed(&workspace)); - QWidget *testWidget = 0; + QWidget *testWidget = nullptr; for (int iteration = 0; iteration < 2; ++iteration) { if (iteration == 0) testWidget = window; @@ -351,13 +376,13 @@ void tst_QMdiSubWindow::setWindowState() void tst_QMdiSubWindow::mainWindowSupport() { - QList<QMdiSubWindow *> windows; + QVector<QMdiSubWindow *> windows; QMdiArea *workspace = new QMdiArea; QMainWindow mainWindow; mainWindow.setCentralWidget(workspace); mainWindow.show(); mainWindow.menuBar()->setVisible(true); - qApp->setActiveWindow(&mainWindow); + QApplication::setActiveWindow(&mainWindow); bool nativeMenuBar = mainWindow.menuBar()->isNativeMenuBar(); // QMainWindow's window title is empty, so on a platform which does NOT have a native menubar, @@ -400,7 +425,7 @@ void tst_QMdiSubWindow::mainWindowSupport() // mainWindow.menuBar() is not visible window->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(window->isMaximized()); QVERIFY(!window->maximizedButtonsWidget()); QVERIFY(!window->maximizedSystemMenuIconWidget()); @@ -410,7 +435,7 @@ void tst_QMdiSubWindow::mainWindowSupport() mainWindow.menuBar()->setVisible(true); window->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(window->isMaximized()); if (!nativeMenuBar) { QVERIFY(window->maximizedButtonsWidget()); @@ -430,7 +455,7 @@ void tst_QMdiSubWindow::mainWindowSupport() nestedWorkspace->addSubWindow(nestedWindow); nestedWindow->widget()->setWindowTitle(QLatin1String("NestedWindow ") + QString::number(i)); nestedWindow->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(nestedWindow->isMaximized()); QVERIFY(!nestedWindow->maximizedButtonsWidget()); QVERIFY(!nestedWindow->maximizedSystemMenuIconWidget()); @@ -445,8 +470,8 @@ void tst_QMdiSubWindow::mainWindowSupport() return; workspace->activateNextSubWindow(); - qApp->processEvents(); - foreach (QMdiSubWindow *window, windows) { + QCoreApplication::processEvents(); + for (QMdiSubWindow *window : qAsConst(windows)) { QCOMPARE(workspace->activeSubWindow(), window); QVERIFY(window->isMaximized()); QVERIFY(window->maximizedButtonsWidget()); @@ -457,7 +482,7 @@ void tst_QMdiSubWindow::mainWindowSupport() QCOMPARE(mainWindow.windowTitle(), QString::fromLatin1("%1 - [%2]") .arg(originalWindowTitle, window->widget()->windowTitle())); workspace->activateNextSubWindow(); - qApp->processEvents(); + QCoreApplication::processEvents(); } } @@ -480,15 +505,16 @@ void tst_QMdiSubWindow::emittingOfSignals() QFETCH(QByteArray, signal); QFETCH(Qt::WindowState, watchedState); QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction())); workspace.show(); - qApp->processEvents(); - qApp->setActiveWindow(&workspace); + QCoreApplication::processEvents(); + QApplication::setActiveWindow(&workspace); QMdiSubWindow *window = qobject_cast<QMdiSubWindow *>(workspace.addSubWindow(new QWidget)); - qApp->processEvents(); + QCoreApplication::processEvents(); window->show(); if (signal != SIGNAL(windowRestored())) - workspace.setActiveSubWindow(0); - qApp->processEvents(); + workspace.setActiveSubWindow(nullptr); + QCoreApplication::processEvents(); QSignalSpy spy(window, signal == SIGNAL(aboutToActivate()) ? signal.data() @@ -523,25 +549,26 @@ void tst_QMdiSubWindow::emittingOfSignals() #endif QCOMPARE(count, 1); - window->setParent(0); + window->setParent(nullptr); window->showNormal(); QVERIFY(QTest::qWaitForWindowExposed(window)); - qApp->processEvents(); + QCoreApplication::processEvents(); spy.clear(); triggerSignal(window, &workspace, signal); QCOMPARE(spy.count(), 0); delete window; - window = 0; + window = nullptr; } void tst_QMdiSubWindow::showShaded() { QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *window = workspace.addSubWindow(new QLineEdit); window->resize(300, 300); - qApp->processEvents(); + QCoreApplication::processEvents(); workspace.show(); QVERIFY(QTest::qWaitForWindowExposed(&workspace)); @@ -588,7 +615,7 @@ void tst_QMdiSubWindow::showShaded() // vertical resize with the mouse. int offset = window->style()->pixelMetric(QStyle::PM_MDIFrameWidth) / 2; QPoint mousePosition(window->width() - qMax(offset, 2), window->height() - qMax(offset, 2)); - QWidget *mouseReceiver = 0; + QWidget *mouseReceiver = nullptr; #ifdef Q_OS_MAC if (window->style()->inherits("QMacStyle")) mouseReceiver = window->findChild<QSizeGrip *>(); @@ -609,7 +636,7 @@ void tst_QMdiSubWindow::showShaded() QCOMPARE(window->height(), minimumSizeHint.height()); window->showShaded(); - window->setParent(0); + window->setParent(nullptr); window->show(); QVERIFY(!window->isShaded()); @@ -630,17 +657,18 @@ void tst_QMdiSubWindow::showNormal() QFETCH(QByteArray, slot); QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QWidget *window = workspace.addSubWindow(new QWidget); - qApp->processEvents(); + QCoreApplication::processEvents(); workspace.show(); window->show(); QVERIFY(QTest::qWaitForWindowExposed(&workspace)); QRect originalGeometry = window->geometry(); QVERIFY(QMetaObject::invokeMethod(window, slot.data())); - qApp->processEvents(); + QCoreApplication::processEvents(); window->showNormal(); - qApp->processEvents(); + QCoreApplication::processEvents(); #ifdef Q_OS_WINRT QEXPECT_FAIL("showMinimized", "Windows are maximized per default on WinRt ", Abort); QEXPECT_FAIL("showMaximized", "Windows are maximized per default on WinRt ", Abort); @@ -651,8 +679,8 @@ void tst_QMdiSubWindow::showNormal() class EventSpy : public QObject { public: - EventSpy(QObject *object, QEvent::Type event) - : eventToSpy(event), _count(0) + explicit EventSpy(QObject *object, QEvent::Type event) + : eventToSpy(event) { if (object) object->installEventFilter(this); @@ -662,7 +690,7 @@ public: void clear() { _count = 0; } protected: - bool eventFilter(QObject *object, QEvent *event) + bool eventFilter(QObject *object, QEvent *event) override { if (event->type() == eventToSpy) ++_count; @@ -670,8 +698,8 @@ protected: } private: - QEvent::Type eventToSpy; - int _count; + const QEvent::Type eventToSpy; + int _count = 0; }; #ifndef QT_NO_CURSOR @@ -696,13 +724,15 @@ void tst_QMdiSubWindow::setOpaqueResizeAndMove() QFETCH(QSize, windowSize); QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + + QLatin1String("::") + QLatin1String(QTest::currentDataTag())); QMdiSubWindow *window = qobject_cast<QMdiSubWindow *>(workspace.addSubWindow(new QWidget)); - qApp->processEvents(); + QCoreApplication::processEvents(); workspace.resize(workspaceSize); workspace.show(); QVERIFY(QTest::qWaitForWindowExposed(&workspace)); - QWidget *mouseReceiver = 0; + QWidget *mouseReceiver = nullptr; if (window->style()->inherits("QMacStyle")) mouseReceiver = window->findChild<QSizeGrip *>(); else @@ -811,81 +841,81 @@ void tst_QMdiSubWindow::setWindowFlags_data() // Standard window types with no custom flags set. QTest::newRow("Qt::Widget") << Qt::Widget << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::Window") << Qt::Window << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::Dialog") << Qt::Dialog << Qt::SubWindow - << Qt::WindowFlags(0) << DialogWindowFlags; + << Qt::WindowFlags{} << DialogWindowFlags; QTest::newRow("Qt::Sheet") << Qt::Sheet << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::Drawer") << Qt::Drawer << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::Popup") << Qt::Popup << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::Tool") << Qt::Tool << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::ToolTip") << Qt::ToolTip << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::SplashScreen") << Qt::SplashScreen << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::Desktop") << Qt::Desktop << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; QTest::newRow("Qt::SubWindow") << Qt::SubWindow << Qt::SubWindow - << Qt::WindowFlags(0) << StandardWindowFlags; + << Qt::WindowFlags{} << StandardWindowFlags; // Custom flags QTest::newRow("Title") << Qt::SubWindow << Qt::SubWindow - << (Qt::WindowTitleHint | Qt::WindowFlags(0)) - << Qt::WindowFlags(0); + << (Qt::WindowTitleHint | Qt::WindowFlags{}) + << Qt::WindowFlags{}; QTest::newRow("TitleAndMin") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowTitleHint | Qt::WindowMinimizeButtonHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("TitleAndMax") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowTitleHint | Qt::WindowMaximizeButtonHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("TitleAndMinMax") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("Standard") << Qt::SubWindow << Qt::SubWindow << StandardWindowFlags - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("StandardAndShade") << Qt::SubWindow << Qt::SubWindow << (StandardWindowFlags | Qt::WindowShadeButtonHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("StandardAndContext") << Qt::SubWindow << Qt::SubWindow << (StandardWindowFlags | Qt::WindowContextHelpButtonHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("StandardAndStaysOnTop") << Qt::SubWindow << Qt::SubWindow << (StandardWindowFlags | Qt::WindowStaysOnTopHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("StandardAndFrameless") << Qt::SubWindow << Qt::SubWindow << (StandardWindowFlags | Qt::FramelessWindowHint) - << (Qt::FramelessWindowHint | Qt::WindowFlags(0)); + << Qt::WindowFlags(Qt::FramelessWindowHint); QTest::newRow("StandardAndFramelessAndStaysOnTop") << Qt::SubWindow << Qt::SubWindow << (StandardWindowFlags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint) << (Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); QTest::newRow("Shade") << Qt::SubWindow << Qt::SubWindow - << (Qt::WindowShadeButtonHint | Qt::WindowFlags(0)) + << (Qt::WindowShadeButtonHint | Qt::WindowFlags{}) << (StandardWindowFlags | Qt::WindowShadeButtonHint); QTest::newRow("ShadeAndCustomize") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowShadeButtonHint | Qt::CustomizeWindowHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("Context") << Qt::SubWindow << Qt::SubWindow - << (Qt::WindowContextHelpButtonHint | Qt::WindowFlags(0)) + << (Qt::WindowContextHelpButtonHint | Qt::WindowFlags{}) << (StandardWindowFlags | Qt::WindowContextHelpButtonHint); QTest::newRow("ContextAndCustomize") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowContextHelpButtonHint | Qt::CustomizeWindowHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("ShadeAndContext") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowShadeButtonHint | Qt::WindowContextHelpButtonHint) << (StandardWindowFlags | Qt::WindowShadeButtonHint | Qt::WindowContextHelpButtonHint); QTest::newRow("ShadeAndContextAndCustomize") << Qt::SubWindow << Qt::SubWindow << (Qt::WindowShadeButtonHint | Qt::WindowContextHelpButtonHint | Qt::CustomizeWindowHint) - << Qt::WindowFlags(0); + << Qt::WindowFlags{}; QTest::newRow("OnlyCustomize") << Qt::SubWindow << Qt::SubWindow - << (Qt::CustomizeWindowHint | Qt::WindowFlags(0)) - << Qt::WindowFlags(0); + << (Qt::CustomizeWindowHint | Qt::WindowFlags{}) + << Qt::WindowFlags{}; } void tst_QMdiSubWindow::setWindowFlags() @@ -896,8 +926,10 @@ void tst_QMdiSubWindow::setWindowFlags() QFETCH(Qt::WindowFlags, expectedCustomFlags); QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + + QLatin1String("::") + QLatin1String(QTest::currentDataTag())); QMdiSubWindow *window = qobject_cast<QMdiSubWindow *>(workspace.addSubWindow(new QWidget)); - qApp->processEvents(); + QCoreApplication::processEvents(); workspace.show(); window->show(); QVERIFY(QTest::qWaitForWindowExposed(&workspace)); @@ -914,8 +946,9 @@ void tst_QMdiSubWindow::setWindowFlags() void tst_QMdiSubWindow::mouseDoubleClick() { QMdiArea workspace; + workspace.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *window = qobject_cast<QMdiSubWindow *>(workspace.addSubWindow(new QWidget)); - qApp->processEvents(); + QCoreApplication::processEvents(); workspace.show(); window->show(); @@ -939,11 +972,11 @@ void tst_QMdiSubWindow::mouseDoubleClick() // Without Qt::WindowShadeButtonHint flag set sendMouseDoubleClick(window, mousePosition); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(window->isMaximized()); sendMouseDoubleClick(window, mousePosition); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!window->isMaximized()); QCOMPARE(window->geometry(), originalGeometry); @@ -952,11 +985,11 @@ void tst_QMdiSubWindow::mouseDoubleClick() QVERIFY(window->windowFlags() & Qt::WindowShadeButtonHint); originalGeometry = window->geometry(); sendMouseDoubleClick(window, mousePosition); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(window->isShaded()); sendMouseDoubleClick(window, mousePosition); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!window->isShaded()); QCOMPARE(window->geometry(), originalGeometry); @@ -976,20 +1009,25 @@ void tst_QMdiSubWindow::setSystemMenu() QCOMPARE(subWindow->actions(), systemMenu->actions()); QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiArea *mdiArea = new QMdiArea; mdiArea->addSubWindow(subWindow); mainWindow.setCentralWidget(mdiArea); mainWindow.menuBar()->setNativeMenuBar(false); - mainWindow.show(); + // Prevent the window from spanning screens + if (QGuiApplication::screens().size() > 1) + mainWindow.showMaximized(); + else + mainWindow.show(); QVERIFY(QTest::qWaitForWindowExposed(&mainWindow)); QTRY_VERIFY(subWindow->isVisible()); QPoint globalPopupPos; // Show system menu - QVERIFY(!qApp->activePopupWidget()); + QVERIFY(!QApplication::activePopupWidget()); subWindow->showSystemMenu(); - QTRY_COMPARE(qApp->activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); + QTRY_COMPARE(QApplication::activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); #ifdef Q_OS_WINRT QEXPECT_FAIL("", "Broken on WinRT - QTBUG-68297", Abort); #endif @@ -997,12 +1035,12 @@ void tst_QMdiSubWindow::setSystemMenu() (globalPopupPos = subWindow->mapToGlobal(subWindow->contentsRect().topLeft())) ); systemMenu->hide(); - QVERIFY(!qApp->activePopupWidget()); + QVERIFY(!QApplication::activePopupWidget()); QTest::ignoreMessage(QtWarningMsg, "QMdiSubWindow::setSystemMenu: system menu is already set"); subWindow->setSystemMenu(systemMenu); - subWindow->setSystemMenu(0); + subWindow->setSystemMenu(nullptr); QVERIFY(!systemMenu); // systemMenu is QPointer systemMenu = new QMenu(subWindow); @@ -1014,13 +1052,13 @@ void tst_QMdiSubWindow::setSystemMenu() QCOMPARE(subWindow->systemMenu()->actions().count(), 1); // Show the new system menu - QVERIFY(!qApp->activePopupWidget()); + QVERIFY(!QApplication::activePopupWidget()); subWindow->showSystemMenu(); - QTRY_COMPARE(qApp->activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); + QTRY_COMPARE(QApplication::activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); QTRY_COMPARE(systemMenu->mapToGlobal(QPoint(0, 0)), globalPopupPos); systemMenu->hide(); - QVERIFY(!qApp->activePopupWidget()); + QVERIFY(!QApplication::activePopupWidget()); #if !defined (Q_OS_DARWIN) // System menu in menu bar. @@ -1029,29 +1067,30 @@ void tst_QMdiSubWindow::setSystemMenu() QWidget *menuLabel = subWindow->maximizedSystemMenuIconWidget(); QVERIFY(menuLabel); subWindow->showSystemMenu(); - QTRY_COMPARE(qApp->activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); + QTRY_COMPARE(QApplication::activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); QCOMPARE(systemMenu->mapToGlobal(QPoint(0, 0)), (globalPopupPos = menuLabel->mapToGlobal(QPoint(0, menuLabel->y() + menuLabel->height())))); systemMenu->hide(); - QTRY_VERIFY(!qApp->activePopupWidget()); + QTRY_VERIFY(!QApplication::activePopupWidget()); subWindow->showNormal(); #endif // Reverse - qApp->setLayoutDirection(Qt::RightToLeft); - qApp->processEvents(); + LayoutDirectionGuard guard; + QApplication::setLayoutDirection(Qt::RightToLeft); + QCoreApplication::processEvents(); mainWindow.updateGeometry(); QTest::qWait(150); subWindow->showSystemMenu(); - QTRY_COMPARE(qApp->activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); + QTRY_COMPARE(QApplication::activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); // + QPoint(1, 0) because topRight() == QPoint(left() + width() -1, top()) globalPopupPos = subWindow->mapToGlobal(subWindow->contentsRect().topRight()) + QPoint(1, 0); globalPopupPos -= QPoint(systemMenu->sizeHint().width(), 0); QTRY_COMPARE(systemMenu->mapToGlobal(QPoint(0, 0)), globalPopupPos); systemMenu->hide(); - QVERIFY(!qApp->activePopupWidget()); + QVERIFY(!QApplication::activePopupWidget()); #if !defined (Q_OS_DARWIN) // System menu in menu bar in reverse mode. @@ -1060,18 +1099,15 @@ void tst_QMdiSubWindow::setSystemMenu() menuLabel = subWindow->maximizedSystemMenuIconWidget(); QVERIFY(menuLabel); subWindow->showSystemMenu(); - QTRY_COMPARE(qApp->activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); + QTRY_COMPARE(QApplication::activePopupWidget(), qobject_cast<QWidget *>(systemMenu)); globalPopupPos = menuLabel->mapToGlobal(QPoint(menuLabel->width(), menuLabel->y() + menuLabel->height())); globalPopupPos -= QPoint(systemMenu->sizeHint().width(), 0); QTRY_COMPARE(systemMenu->mapToGlobal(QPoint(0, 0)), globalPopupPos); #endif delete systemMenu; - QVERIFY(!qApp->activePopupWidget()); + QVERIFY(!QApplication::activePopupWidget()); QVERIFY(!subWindow->systemMenu()); - - // Restore layout direction. - qApp->setLayoutDirection(Qt::LeftToRight); } void tst_QMdiSubWindow::restoreFocus() @@ -1097,7 +1133,7 @@ void tst_QMdiSubWindow::restoreFocus() QMdiArea *nestedWorkspace = new QMdiArea; for (int i = 0; i < 4; ++i) nestedWorkspace->addSubWindow(new QTextEdit)->show(); - qApp->processEvents(); + QCoreApplication::processEvents(); nestedWorkspace->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); nestedWorkspace->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); box4->layout()->addWidget(nestedWorkspace); @@ -1112,76 +1148,76 @@ void tst_QMdiSubWindow::restoreFocus() // Add complex widget to workspace. QMdiArea topArea; + topArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *complexWindow = topArea.addSubWindow(box); topArea.show(); box->show(); - qApp->setActiveWindow(&topArea); + QApplication::setActiveWindow(&topArea); QMdiSubWindow *expectedFocusWindow = nestedWorkspace->subWindowList().last(); QVERIFY(expectedFocusWindow); QVERIFY(expectedFocusWindow->widget()); - QCOMPARE(qApp->focusWidget(), expectedFocusWindow->widget()); + QCOMPARE(QApplication::focusWidget(), expectedFocusWindow->widget()); // Normal -> minimized expectedFocusWindow->showMinimized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(expectedFocusWindow->isMinimized()); - qDebug() << expectedFocusWindow<< qApp->focusWidget(); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(expectedFocusWindow)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(expectedFocusWindow)); // Minimized -> normal expectedFocusWindow->showNormal(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!expectedFocusWindow->isMinimized()); - QCOMPARE(qApp->focusWidget(), expectedFocusWindow->widget()); + QCOMPARE(QApplication::focusWidget(), expectedFocusWindow->widget()); // Normal -> maximized expectedFocusWindow->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(expectedFocusWindow->isMaximized()); - QCOMPARE(qApp->focusWidget(), expectedFocusWindow->widget()); + QCOMPARE(QApplication::focusWidget(), expectedFocusWindow->widget()); // Maximized -> normal expectedFocusWindow->showNormal(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!expectedFocusWindow->isMaximized()); - QCOMPARE(qApp->focusWidget(), expectedFocusWindow->widget()); + QCOMPARE(QApplication::focusWidget(), expectedFocusWindow->widget()); // Minimized -> maximized expectedFocusWindow->showMinimized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(expectedFocusWindow->isMinimized()); expectedFocusWindow->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(expectedFocusWindow->isMaximized()); - QCOMPARE(qApp->focusWidget(), expectedFocusWindow->widget()); + QCOMPARE(QApplication::focusWidget(), expectedFocusWindow->widget()); // Maximized -> minimized expectedFocusWindow->showNormal(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!expectedFocusWindow->isMaximized()); expectedFocusWindow->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(expectedFocusWindow->isMaximized()); expectedFocusWindow->showMinimized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(expectedFocusWindow->isMinimized()); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(expectedFocusWindow)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(expectedFocusWindow)); complexWindow->showMinimized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(complexWindow->isMinimized()); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(complexWindow)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(complexWindow)); complexWindow->showNormal(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!complexWindow->isMinimized()); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(expectedFocusWindow)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(expectedFocusWindow)); } class MultiWidget : public QWidget { public: - explicit MultiWidget(QWidget *parent = 0) : QWidget(parent) + explicit MultiWidget(QWidget *parent = nullptr) : QWidget(parent) , m_lineEdit1(new QLineEdit(this)), m_lineEdit2(new QLineEdit(this)) { QVBoxLayout *lt = new QVBoxLayout(this); @@ -1237,28 +1273,29 @@ void tst_QMdiSubWindow::changeFocusWithTab() widget->layout()->addWidget(thirdLineEdit); QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.addSubWindow(widget); mdiArea.show(); QCOMPARE(mdiArea.subWindowList().count(), 1); - qApp->setActiveWindow(&mdiArea); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(firstLineEdit)); + QApplication::setActiveWindow(&mdiArea); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(firstLineEdit)); // Next QTest::keyPress(widget, Qt::Key_Tab); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(secondLineEdit)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(secondLineEdit)); // Next QTest::keyPress(widget, Qt::Key_Tab); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(thirdLineEdit)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(thirdLineEdit)); // Previous QTest::keyPress(widget, Qt::Key_Backtab); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(secondLineEdit)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(secondLineEdit)); // Previous QTest::keyPress(widget, Qt::Key_Backtab); - QCOMPARE(qApp->focusWidget(), static_cast<QWidget *>(firstLineEdit)); + QCOMPARE(QApplication::focusWidget(), static_cast<QWidget *>(firstLineEdit)); QMdiSubWindow *window = mdiArea.addSubWindow(new QPushButton); window->show(); @@ -1269,31 +1306,32 @@ void tst_QMdiSubWindow::changeFocusWithTab() // focus (which is the case for a QPushButton). QTest::keyPress(window, Qt::Key_Tab); QCOMPARE(mdiArea.activeSubWindow(), window); - QCOMPARE(qApp->focusWidget(), tabAllWidgets() ? window->widget() : window); + QCOMPARE(QApplication::focusWidget(), tabAllWidgets() ? window->widget() : window); QTest::keyPress(window, Qt::Key_Tab); QCOMPARE(mdiArea.activeSubWindow(), window); - QCOMPARE(qApp->focusWidget(), tabAllWidgets() ? window->widget() : window); + QCOMPARE(QApplication::focusWidget(), tabAllWidgets() ? window->widget() : window); } class MyTextEdit : public QTextEdit { public: - MyTextEdit(QWidget *parent = 0) : QTextEdit(parent), acceptClose(false) {} + using QTextEdit::QTextEdit; void setAcceptClose(bool enable = true) { acceptClose = enable; } protected: - void closeEvent(QCloseEvent *closeEvent) + void closeEvent(QCloseEvent *closeEvent) override { if (!acceptClose) closeEvent->ignore(); } private: - bool acceptClose; + bool acceptClose = false; }; void tst_QMdiSubWindow::closeEvent() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.show(); MyTextEdit *textEdit = new MyTextEdit; @@ -1379,7 +1417,7 @@ void tst_QMdiSubWindow::setWindowTitle() textEdit->setWindowModified(true); QVERIFY(window->isWindowModified()); - window->setWidget(0); + window->setWidget(nullptr); QCOMPARE(window->windowTitle(), QString()); QVERIFY(!window->isWindowModified()); delete textEdit; @@ -1405,6 +1443,8 @@ void tst_QMdiSubWindow::resizeEvents() QFETCH(bool, isShadeMode); QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + + QLatin1String("::") + QLatin1String(QTest::currentDataTag())); QMdiArea *mdiArea = new QMdiArea; mainWindow.setCentralWidget(mdiArea); mainWindow.show(); @@ -1483,6 +1523,7 @@ void tst_QMdiSubWindow::hideAndShow() // Set the tab widget as the central widget in QMainWindow. QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mainWindow.setGeometry(0, 0, 640, 480); QMenuBar *menuBar = mainWindow.menuBar(); menuBar->setNativeMenuBar(false); @@ -1524,7 +1565,7 @@ void tst_QMdiSubWindow::hideAndShow() // Show QMdiArea. tabWidget->setCurrentIndex(0); - qApp->processEvents(); + QCoreApplication::processEvents(); subWindow = mdiArea->subWindowList().back(); QVERIFY(subWindow); @@ -1544,7 +1585,8 @@ void tst_QMdiSubWindow::hideAndShow() QVERIFY(!menuBar->cornerWidget(Qt::TopRightCorner)); // Check that newly added windows got right sizes. - foreach (QMdiSubWindow *window, mdiArea->subWindowList()) + const auto subWindowList = mdiArea->subWindowList(); + for (QMdiSubWindow *window : subWindowList) QCOMPARE(window->size(), window->sizeHint()); subWindow->showMaximized(); @@ -1582,6 +1624,7 @@ void tst_QMdiSubWindow::hideAndShow() void tst_QMdiSubWindow::keepWindowMaximizedState() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *subWindow = mdiArea.addSubWindow(new QTextEdit); mdiArea.show(); QVERIFY(QTest::qWaitForWindowExposed(&mdiArea)); @@ -1619,6 +1662,7 @@ void tst_QMdiSubWindow::keepWindowMaximizedState() void tst_QMdiSubWindow::explicitlyHiddenWidget() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QTextEdit *textEdit = new QTextEdit; textEdit->hide(); QMdiSubWindow *subWindow = mdiArea.addSubWindow(textEdit); @@ -1657,7 +1701,7 @@ void tst_QMdiSubWindow::explicitlyHiddenWidget() textEdit->show(); subWindow->showMinimized(); - subWindow->setWidget(0); + subWindow->setWidget(nullptr); delete textEdit; textEdit = new QTextEdit; textEdit->hide(); @@ -1670,6 +1714,7 @@ void tst_QMdiSubWindow::explicitlyHiddenWidget() void tst_QMdiSubWindow::resizeTimer() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *subWindow = mdiArea.addSubWindow(new QWidget); mdiArea.show(); QVERIFY(QTest::qWaitForWindowExposed(&mdiArea)); @@ -1679,7 +1724,7 @@ void tst_QMdiSubWindow::resizeTimer() for (int i = 0; i < 20; ++i) { subWindow->resize(subWindow->size() + QSize(2, 2)); - qApp->processEvents(); + QCoreApplication::processEvents(); } QTest::qWait(500); // Wait for timer events to occur. @@ -1690,6 +1735,7 @@ void tst_QMdiSubWindow::resizeTimer() void tst_QMdiSubWindow::fixedMinMaxSize() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.setGeometry(0, 0, 640, 480); mdiArea.show(); QVERIFY(QTest::qWaitForWindowExposed(&mdiArea)); @@ -1748,49 +1794,51 @@ void tst_QMdiSubWindow::replaceMenuBarWhileMaximized() { QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiArea *mdiArea = new QMdiArea; QMdiSubWindow *subWindow = mdiArea->addSubWindow(new QTextEdit); subWindow->showMaximized(); mainWindow.setCentralWidget(mdiArea); - QMenuBar *menuBar = mainWindow.menuBar(); - menuBar->setNativeMenuBar(false); + QMenuBar *menuBar1 = mainWindow.menuBar(); + menuBar1->setNativeMenuBar(false); mainWindow.show(); QVERIFY(QTest::qWaitForWindowExposed(&mainWindow)); - qApp->processEvents(); + QCoreApplication::processEvents(); #if defined Q_OS_QNX QEXPECT_FAIL("", "QTBUG-38231", Abort); #endif QVERIFY(subWindow->maximizedButtonsWidget()); QVERIFY(subWindow->maximizedSystemMenuIconWidget()); - QCOMPARE(menuBar->cornerWidget(Qt::TopLeftCorner), subWindow->maximizedSystemMenuIconWidget()); - QCOMPARE(menuBar->cornerWidget(Qt::TopRightCorner), subWindow->maximizedButtonsWidget()); + QCOMPARE(menuBar1->cornerWidget(Qt::TopLeftCorner), subWindow->maximizedSystemMenuIconWidget()); + QCOMPARE(menuBar1->cornerWidget(Qt::TopRightCorner), subWindow->maximizedButtonsWidget()); // Replace. - mainWindow.setMenuBar(new QMenuBar); - menuBar = mainWindow.menuBar(); - menuBar->setNativeMenuBar(false); - qApp->processEvents(); + auto menuBar2 = new QMenuBar; + mainWindow.setMenuBar(menuBar2); + menuBar2->setNativeMenuBar(false); + QCoreApplication::processEvents(); QVERIFY(subWindow->maximizedButtonsWidget()); QVERIFY(subWindow->maximizedSystemMenuIconWidget()); - QCOMPARE(menuBar->cornerWidget(Qt::TopLeftCorner), subWindow->maximizedSystemMenuIconWidget()); - QCOMPARE(menuBar->cornerWidget(Qt::TopRightCorner), subWindow->maximizedButtonsWidget()); + QCOMPARE(menuBar2->cornerWidget(Qt::TopLeftCorner), subWindow->maximizedSystemMenuIconWidget()); + QCOMPARE(menuBar2->cornerWidget(Qt::TopRightCorner), subWindow->maximizedButtonsWidget()); subWindow->showNormal(); QVERIFY(!subWindow->maximizedButtonsWidget()); QVERIFY(!subWindow->maximizedSystemMenuIconWidget()); - QVERIFY(!menuBar->cornerWidget(Qt::TopLeftCorner)); - QVERIFY(!menuBar->cornerWidget(Qt::TopRightCorner)); + QVERIFY(!menuBar2->cornerWidget(Qt::TopLeftCorner)); + QVERIFY(!menuBar2->cornerWidget(Qt::TopRightCorner)); // Delete and replace. subWindow->showMaximized(); - delete menuBar; - mainWindow.setMenuBar(new QMenuBar); - qApp->processEvents(); + delete menuBar2; + auto menuBar3 = new QMenuBar; + mainWindow.setMenuBar(menuBar3); + QCoreApplication::processEvents(); QVERIFY(!subWindow->maximizedButtonsWidget()); QVERIFY(!subWindow->maximizedSystemMenuIconWidget()); @@ -1801,8 +1849,8 @@ void tst_QMdiSubWindow::replaceMenuBarWhileMaximized() // Delete. subWindow->showMaximized(); - mainWindow.setMenuBar(0); - qApp->processEvents(); + mainWindow.setMenuBar(nullptr); + QCoreApplication::processEvents(); QVERIFY(!mainWindow.menuWidget()); QVERIFY(!subWindow->maximizedButtonsWidget()); @@ -1811,6 +1859,8 @@ void tst_QMdiSubWindow::replaceMenuBarWhileMaximized() subWindow->showNormal(); QVERIFY(!subWindow->maximizedButtonsWidget()); QVERIFY(!subWindow->maximizedSystemMenuIconWidget()); + delete menuBar1; + delete menuBar3; } void tst_QMdiSubWindow::closeOnDoubleClick_data() @@ -1842,9 +1892,9 @@ void tst_QMdiSubWindow::closeOnDoubleClick() const QRect actionGeometry = systemMenu->actionGeometry(systemMenu->actions().at(actionIndex)); sendMouseDoubleClick(systemMenu, actionGeometry.center()); - if (qApp->activePopupWidget() == static_cast<QWidget *>(systemMenu)) + if (QApplication::activePopupWidget() == static_cast<QWidget *>(systemMenu)) systemMenu->hide(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(!systemMenu || !systemMenu->isVisible()); QCOMPARE(subWindow.isNull() || !subWindow->isVisible(), expectClosed); } @@ -1854,6 +1904,7 @@ void tst_QMdiSubWindow::setFont() { QSKIP("This test function is unstable in CI, please see QTBUG-22544"); QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *subWindow = mdiArea.addSubWindow(new QPushButton(QLatin1String("test"))); subWindow->resize(300, 100); subWindow->setWindowTitle(QLatin1String("Window title")); @@ -1871,7 +1922,7 @@ void tst_QMdiSubWindow::setFont() QFont newFont(QLatin1String("Helvetica"), 16); newFont.setBold(true); subWindow->setFont(newFont); - qApp->processEvents(); + QCoreApplication::processEvents(); const QFont &swFont = subWindow->font(); QCOMPARE(swFont.family(), newFont.family()); QCOMPARE(swFont.pointSize(), newFont.pointSize()); @@ -1880,7 +1931,7 @@ void tst_QMdiSubWindow::setFont() QVERIFY(newTitleBar != originalTitleBar); subWindow->setFont(originalFont); - qApp->processEvents(); + QCoreApplication::processEvents(); QCOMPARE(subWindow->font(), originalFont); newTitleBar = subWindow->grab(titleBarRect).toImage(); QCOMPARE(newTitleBar, originalTitleBar); @@ -1889,6 +1940,7 @@ void tst_QMdiSubWindow::setFont() void tst_QMdiSubWindow::task_188849() { QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); // Sets a regular QWidget (and NOT a QMenuBar) as the menu bar. mainWindow.setMenuWidget(new QWidget); @@ -1907,10 +1959,11 @@ void tst_QMdiSubWindow::task_188849() void tst_QMdiSubWindow::mdiArea() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); QMdiSubWindow *subWindow = mdiArea.addSubWindow(new QWidget); QCOMPARE(subWindow->mdiArea(), &mdiArea); - subWindow->setParent(0); + subWindow->setParent(nullptr); QVERIFY(!subWindow->mdiArea()); // Child of the area's corner widget. @@ -1931,10 +1984,11 @@ void tst_QMdiSubWindow::task_182852() { QMdiArea *workspace = new QMdiArea; QMainWindow mainWindow; + mainWindow.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mainWindow.setCentralWidget(workspace); mainWindow.show(); mainWindow.menuBar()->setVisible(true); - qApp->setActiveWindow(&mainWindow); + QApplication::setActiveWindow(&mainWindow); if (mainWindow.menuBar()->isNativeMenuBar()) return; // The main window's title is not overwritten if we have a native menubar (macOS, Unity etc.) @@ -1950,7 +2004,7 @@ void tst_QMdiSubWindow::task_182852() workspace->addSubWindow(window); window->showMaximized(); - qApp->processEvents(); + QCoreApplication::processEvents(); QVERIFY(window->isMaximized()); QCOMPARE(mainWindow.windowTitle(), QString::fromLatin1("%1 - [%2]") @@ -1977,6 +2031,7 @@ void tst_QMdiSubWindow::task_182852() void tst_QMdiSubWindow::task_233197() { QMainWindow *mainWindow = new QMainWindow; + mainWindow->setWindowTitle(QLatin1String(QTest::currentTestFunction())); mainWindow->setAttribute(Qt::WA_DeleteOnClose); mainWindow->resize(500, 200); mainWindow->show(); @@ -2001,17 +2056,19 @@ void tst_QMdiSubWindow::task_233197() Q_UNUSED(menuBar); QPushButton *focus1 = new QPushButton(QLatin1String("Focus 1"), mainWindow); - QObject::connect(focus1, SIGNAL(clicked()), subWindow1, SLOT(setFocus())); + QObject::connect(focus1, &QAbstractButton::clicked, subWindow1, + QOverload<>::of(&QWidget::setFocus)); focus1->move(5, 30); focus1->show(); QPushButton *focus2 = new QPushButton(QLatin1String("Focus 2"), mainWindow); - QObject::connect(focus2, SIGNAL(clicked()), subWindow2, SLOT(setFocus())); + QObject::connect(focus2, &QAbstractButton::clicked, subWindow2, + QOverload<>::of(&QWidget::setFocus)); focus2->move(5, 60); focus2->show(); QPushButton *close = new QPushButton(QLatin1String("Close"), mainWindow); - QObject::connect(close, SIGNAL(clicked()), mainWindow, SLOT(close())); + QObject::connect(close, &QAbstractButton::clicked, mainWindow, &QWidget::close); close->move(5, 90); close->show(); @@ -2035,6 +2092,7 @@ void tst_QMdiSubWindow::task_233197() void tst_QMdiSubWindow::task_226929() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.show(); QVERIFY(QTest::qWaitForWindowExposed(&mdiArea)); @@ -2056,6 +2114,7 @@ void tst_QMdiSubWindow::task_226929() void tst_QMdiSubWindow::styleChange() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.show(); QVERIFY(QTest::qWaitForWindowExposed(&mdiArea)); @@ -2070,7 +2129,7 @@ void tst_QMdiSubWindow::styleChange() QTest::qWait(100); qRegisterMetaType<QMdiSubWindow *>(); - QSignalSpy spy(&mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*))); + QSignalSpy spy(&mdiArea, &QMdiArea::subWindowActivated); QVERIFY(spy.isValid()); QEvent event(QEvent::StyleChange); @@ -2085,6 +2144,7 @@ void tst_QMdiSubWindow::styleChange() void tst_QMdiSubWindow::testFullScreenState() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.showMaximized(); QMdiSubWindow *subWindow = mdiArea.addSubWindow(new QWidget); @@ -2101,6 +2161,7 @@ void tst_QMdiSubWindow::testFullScreenState() void tst_QMdiSubWindow::testRemoveBaseWidget() { QMdiArea mdiArea; + mdiArea.setWindowTitle(QLatin1String(QTest::currentTestFunction())); mdiArea.show(); QWidget *widget1 = new QWidget; diff --git a/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp b/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp index b9d6888263..7bce23af26 100644 --- a/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp +++ b/tests/auto/widgets/widgets/qspinbox/tst_qspinbox.cpp @@ -461,26 +461,30 @@ void tst_QSpinBox::setPrefixSuffix() QFETCH(QString, expectedCleanText); QFETCH(bool, show); - QSpinBox spin(0); + QSpinBox spin; + if (show) { + spin.show(); + spin.setPrefix(QString()); // trigger a recalc of sizeHint + } const QSize size1 = spin.sizeHint(); spin.setPrefix(prefix); const QSize size2 = spin.sizeHint(); spin.setSuffix(suffix); const QSize size3 = spin.sizeHint(); spin.setValue(value); - if (show) - spin.show(); QCOMPARE(spin.prefix(), prefix); QCOMPARE(spin.suffix(), suffix); QCOMPARE(spin.text(), expectedText); QCOMPARE(spin.cleanText(), expectedCleanText); - if (!prefix.isEmpty() && !suffix.isEmpty()) { - QVERIFY(size1.width() < size2.width()); + if (!suffix.isEmpty()) { QVERIFY(size2.width() < size3.width()); spin.setSuffix(QString()); QCOMPARE(spin.sizeHint(), size2); + } + if (!prefix.isEmpty()) { + QVERIFY(size1.width() < size2.width()); spin.setPrefix(QString()); QCOMPARE(spin.sizeHint(), size1); } |