diff options
Diffstat (limited to 'tests')
91 files changed, 2272 insertions, 329 deletions
diff --git a/tests/auto/android/runtests_androiddeployqt.pl b/tests/auto/android/runtests_androiddeployqt.pl index d3c9a7bc11..1cc52d0495 100755 --- a/tests/auto/android/runtests_androiddeployqt.pl +++ b/tests/auto/android/runtests_androiddeployqt.pl @@ -53,6 +53,8 @@ use Pod::Usage; my @stack = cwd; my $device_serial=""; # "-s device_serial"; my $deployqt_device_serial=""; # "-device device_serial"; +my $log_out="xml"; +my $max_runtime = 5; my $className="org.qtproject.qt5.android.bindings.QtActivity"; my $jobs = 4; my $testsubset = ""; @@ -75,6 +77,8 @@ GetOptions('h|help' => \$help , 't|test=s' => \$testsubset , 'c|clean' => \$make_clean , 'j|jobs=i' => \$jobs + , 'logtype=s' => \$log_out + , 'runtime=i' => \$max_runtime , 'sdk=s' => \$android_sdk_dir , 'ndk=s' => \$android_ndk_dir , 'toolchain=s' => \$android_toolchain_version @@ -102,7 +106,6 @@ if ($android_to_connect ne ""){ $device_serial =$android_to_connect; } - system("$adb_tool devices") == 0 or die "No device found, please plug/start at least one device/emulator\n"; # make sure we have at least on device attached $deployqt_device_serial = "--device $device_serial" if ($device_serial); @@ -171,6 +174,8 @@ my $temp_dir=tempdir(CLEANUP => 1); my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); my $output_dir=$stack[0]."/".(1900+$year)."-$mon-$mday-$hour:$min"; mkdir($output_dir); +unlink("latest"); +system(" ln -s $output_dir latest"); my $sdk_api=0; my $output = `$adb_tool $device_serial shell getprop`; # get device properties if ($output =~ m/.*\[ro.build.version.sdk\]: \[(\d+)\]/) @@ -186,8 +191,22 @@ sub startTest my $packageName = "org.qtproject.example.tst_$testName"; my $intentName = "$packageName/org.qtproject.qt5.android.bindings.QtActivity"; my $output_file = shift; + my $get_xml= 0; + my $get_txt= 0; + my $testLib =""; + if ($log_out eq "xml") { + $testLib="-o /data/data/$packageName/output.xml,xml"; + $get_xml = 1; + } elsif ($log_out eq "txt") { + $testLib="-o /data/data/$packageName/output.txt,txt"; + $get_txt = 1; + } else { + $testLib="-o /data/data/$packageName/output.xml,xml -o /data/data/$packageName/output.txt,txt"; + $get_xml = 1; + $get_txt = 1; + } - system("$adb_tool $device_serial shell am start -e applicationArguments \"-o /data/data/$packageName/output.xml\" -n $intentName"); # start intent + system("$adb_tool $device_serial shell am start -e applicationArguments \"$testLib\" -n $intentName"); # start intent #wait to start (if it has not started and quit already) waitForProcess($packageName,1,10); @@ -198,7 +217,8 @@ sub startTest print "Someone should kill $packageName\n"; return 1; } - system("$adb_tool $device_serial pull /data/data/$packageName/output.xml $output_dir/$output_file"); + system("$adb_tool $device_serial pull /data/data/$packageName/output.xml $output_dir/$output_file.xml") if ($get_xml); + system("$adb_tool $device_serial pull /data/data/$packageName/output.txt $output_dir/$output_file.txt") if ($get_txt); return 1; } @@ -228,7 +248,7 @@ foreach (split("\n",$testsFiles)) $output_name =~ s/\///; # remove first "/" character $output_name =~ s/\//_/g; # replace all "/" with "_" $output_name=$application unless($output_name); - $time_out=5*60/5; # 5 minutes time out for a normal test + $time_out=$max_runtime*60/5; # 5 minutes time out for a normal test $applicationLibrary = `find $temp_dir -name libtst_bench_$application.so`; @@ -248,7 +268,7 @@ foreach (split("\n",$testsFiles)) } else { - startTest($application, "$output_name.xml") or warn "Can't run $application ...\n"; + startTest($application, "$output_name") or warn "Can't run $application ...\n"; } popd(); @@ -306,6 +326,14 @@ Android strip tool path, used to deploy qt libs. Android readelf tool path, used to check if a test application uses qt OpenGL. +=item B<--logtype = xml|txt|both> + +The format of log file, default is xml. + +=item B<--runtime = minutes> + +The timeout period before stopping individual tests from running. + =item B<-h --help> Print a brief help message and exits. diff --git a/tests/auto/corelib/global/qflags/tst_qflags.cpp b/tests/auto/corelib/global/qflags/tst_qflags.cpp index e50a6b63fe..73a69a1309 100644 --- a/tests/auto/corelib/global/qflags/tst_qflags.cpp +++ b/tests/auto/corelib/global/qflags/tst_qflags.cpp @@ -99,7 +99,7 @@ void tst_QFlags::testFlagMultiBits() const } } -template <int N, typename T> bool verifyConstExpr(T n) { return n == N; } +template <unsigned int N, typename T> bool verifyConstExpr(T n) { return n == N; } void tst_QFlags::constExpr() { diff --git a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp index 4a50a45ea6..0d08e912f8 100644 --- a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp +++ b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp @@ -59,6 +59,7 @@ private slots: void qCoreAppStartupFunctionRestart(); void isEnum(); void qAlignOf(); + void integerForSize(); }; void tst_QGlobal::qIsNull() @@ -566,5 +567,19 @@ void tst_QGlobal::qAlignOf() #undef TEST_AlignOf_RValueRef #undef TEST_AlignOf_impl +void tst_QGlobal::integerForSize() +{ + // compile-only test: + Q_STATIC_ASSERT(sizeof(QIntegerForSize<1>::Signed) == 1); + Q_STATIC_ASSERT(sizeof(QIntegerForSize<2>::Signed) == 2); + Q_STATIC_ASSERT(sizeof(QIntegerForSize<4>::Signed) == 4); + Q_STATIC_ASSERT(sizeof(QIntegerForSize<8>::Signed) == 8); + + Q_STATIC_ASSERT(sizeof(QIntegerForSize<1>::Unsigned) == 1); + Q_STATIC_ASSERT(sizeof(QIntegerForSize<2>::Unsigned) == 2); + Q_STATIC_ASSERT(sizeof(QIntegerForSize<4>::Unsigned) == 4); + Q_STATIC_ASSERT(sizeof(QIntegerForSize<8>::Unsigned) == 8); +} + QTEST_APPLESS_MAIN(tst_QGlobal) #include "tst_qglobal.moc" diff --git a/tests/auto/corelib/io/qfileselector/platforms/+generic_unix/test b/tests/auto/corelib/io/qfileselector/platforms/+android/test2 index e69de29bb2..e69de29bb2 100644 --- a/tests/auto/corelib/io/qfileselector/platforms/+generic_unix/test +++ b/tests/auto/corelib/io/qfileselector/platforms/+android/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/+blackberry/test2 b/tests/auto/corelib/io/qfileselector/platforms/+blackberry/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+blackberry/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/+ios/test2 b/tests/auto/corelib/io/qfileselector/platforms/+ios/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+ios/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/+linux/test2 b/tests/auto/corelib/io/qfileselector/platforms/+linux/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+linux/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/+mac/test b/tests/auto/corelib/io/qfileselector/platforms/+mac/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+mac/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+mac/test2 b/tests/auto/corelib/io/qfileselector/platforms/+mac/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+mac/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+android/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+android/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+android/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+blackberry/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+blackberry/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+blackberry/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+ios/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+ios/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+ios/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+linux/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+linux/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+linux/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/+mac/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/+mac/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/+mac/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+unix/test b/tests/auto/corelib/io/qfileselector/platforms/+unix/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+unix/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+wince/test2 b/tests/auto/corelib/io/qfileselector/platforms/+wince/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+wince/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/+windows/+wince/test b/tests/auto/corelib/io/qfileselector/platforms/+windows/+wince/test new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+windows/+wince/test diff --git a/tests/auto/corelib/io/qfileselector/platforms/+windows/test2 b/tests/auto/corelib/io/qfileselector/platforms/+windows/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/+windows/test2 diff --git a/tests/auto/corelib/io/qfileselector/platforms/test2 b/tests/auto/corelib/io/qfileselector/platforms/test2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/auto/corelib/io/qfileselector/platforms/test2 diff --git a/tests/auto/corelib/io/qfileselector/qfileselector.qrc b/tests/auto/corelib/io/qfileselector/qfileselector.qrc index c644e41107..abfead2a55 100644 --- a/tests/auto/corelib/io/qfileselector/qfileselector.qrc +++ b/tests/auto/corelib/io/qfileselector/qfileselector.qrc @@ -11,13 +11,27 @@ <file>extras/+custom3/+custom5/test</file> <file>extras/+custom5/+custom3/test</file> <file>platforms/test</file> + <file>platforms/+unix/+android/test</file> + <file>platforms/+unix/+blackberry/test</file> + <file>platforms/+unix/+ios/test</file> + <file>platforms/+unix/+mac/test</file> + <file>platforms/+windows/+wince/test</file> + <file>platforms/+windows/test</file> + <file>platforms/+windows/test2</file> + <file>platforms/+unix/+linux/test</file> + <file>platforms/+unix/test</file> + <file>platforms/test2</file> + <file>platforms/+android/test2</file> + <file>platforms/+blackberry/test2</file> + <file>platforms/+ios/test2</file> + <file>platforms/+mac/test2</file> + <file>platforms/+linux/test2</file> + <file>platforms/+wince/test2</file> <file>platforms/+android/test</file> <file>platforms/+blackberry/test</file> <file>platforms/+ios/test</file> - <file>platforms/+osx/test</file> - <file>platforms/+wince/test</file> - <file>platforms/+windows/test</file> + <file>platforms/+mac/test</file> <file>platforms/+linux/test</file> - <file>platforms/+generic_unix/test</file> + <file>platforms/+wince/test</file> </qresource> </RCC> diff --git a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp index 2baebd0296..d6461c3aba 100644 --- a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp +++ b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp @@ -91,9 +91,33 @@ void tst_QFileSelector::basicTest_data() QTest::addColumn<QString>("expectedPath"); QString test("/test");// '/' is here so dir string can also be selector string - QTest::newRow("platform") << QString(":/platforms/test") << QStringList() - << QString(":/platforms/") + QLatin1Char(selectorIndicator) - + QFileSelectorPrivate::platformSelectors().first() + test; + QString test2("/test2"); + QString expectedPlatform1File(":/platforms"); + QString expectedPlatform2File(""); //Only the last selector +#if defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID) && !defined(Q_OS_BLACKBERRY) && !defined(Q_OS_IOS) && !defined(Q_OS_LINUX) && !defined(Q_OS_MAC) + /* We are only aware of specific unixes, and do not have test files for any of the others. + However those unixes can get a selector added from the result of a uname call, so this will + lead to a case where we don't have that file so we can't expect the concatenation of platform + selectors to work. It should just find the +unix/test file.*/ + expectedPlatform1File = QString(":/platforms/") + QLatin1Char(selectorIndicator) + + QString("unix/test"); + expectedPlatform2File = QString(":/platforms/test2"); +#else + foreach (const QString &selector, QFileSelectorPrivate::platformSelectors()) { + expectedPlatform1File = expectedPlatform1File + QLatin1Char('/') + QLatin1Char(selectorIndicator) + + selector; + expectedPlatform2File = selector; + } + expectedPlatform1File += test; + expectedPlatform2File = QLatin1String(":/platforms/") + QLatin1Char(selectorIndicator) + + expectedPlatform2File + test2; +#endif + + QTest::newRow("platform1") << QString(":/platforms/test") << QStringList() + << expectedPlatform1File; + + QTest::newRow("platform2") << QString(":/platforms/test2") << QStringList() + << expectedPlatform2File; QString resourceTestPath(":/extras/test"); QString custom1("custom1"); diff --git a/tests/auto/corelib/io/qloggingcategory/tst_qloggingcategory.cpp b/tests/auto/corelib/io/qloggingcategory/tst_qloggingcategory.cpp index a49793c3d4..50268f20a4 100644 --- a/tests/auto/corelib/io/qloggingcategory/tst_qloggingcategory.cpp +++ b/tests/auto/corelib/io/qloggingcategory/tst_qloggingcategory.cpp @@ -69,7 +69,6 @@ QByteArray qMyMessageFormatString(QtMsgType type, const QMessageLogContext &cont case QtWarningMsg: message.append(".warning"); break; case QtCriticalMsg:message.append(".critical"); break; case QtFatalMsg: message.append(".fatal"); break; - case QtTraceMsg: message.append(".trace"); break; } message.append(": "); message.append(qPrintable(str)); diff --git a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp index c3a1ad206d..d19f4379c7 100644 --- a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp +++ b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp @@ -56,7 +56,7 @@ #define Q_XDG_PLATFORM #endif -const int MaxStandardLocation = QStandardPaths::GenericCacheLocation; +static const int MaxStandardLocation = QStandardPaths::GenericConfigLocation; class tst_qstandardpaths : public QObject { @@ -127,7 +127,8 @@ static const char * const enumNames[MaxStandardLocation + 1 - int(QStandardPaths "RuntimeLocation", "ConfigLocation", "DownloadLocation", - "GenericCacheLocation" + "GenericCacheLocation", + "GenericConfigLocation" }; void tst_qstandardpaths::dump() @@ -151,9 +152,11 @@ void tst_qstandardpaths::testDefaultLocations() const QString expectedConfHome = QDir::homePath() + QString::fromLatin1("/.config"); QCOMPARE(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation), expectedConfHome); + QCOMPARE(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation), expectedConfHome); const QStringList confDirs = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation); QCOMPARE(confDirs.count(), 2); QVERIFY(confDirs.contains(expectedConfHome)); + QCOMPARE(QStandardPaths::standardLocations(QStandardPaths::GenericConfigLocation), confDirs); const QStringList genericDataDirs = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation); QCOMPARE(genericDataDirs.count(), 3); @@ -178,6 +181,7 @@ void tst_qstandardpaths::testCustomLocations() // test writableLocation() QCOMPARE(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation), m_localConfigDir); + QCOMPARE(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation), m_localConfigDir); // test locate() const QString thisFileName = QString::fromLatin1("aFile"); @@ -212,6 +216,7 @@ void tst_qstandardpaths::enableTestMode() // ConfigLocation const QString configDir = qttestDir + QLatin1String("/config"); QCOMPARE(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation), configDir); + QCOMPARE(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation), configDir); const QStringList confDirs = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation); QCOMPARE(confDirs, QStringList() << configDir << m_globalConfigDir); @@ -235,6 +240,7 @@ void tst_qstandardpaths::enableTestMode() testLocations.insert(QStandardPaths::DataLocation, QStandardPaths::writableLocation(QStandardPaths::DataLocation)); testLocations.insert(QStandardPaths::GenericDataLocation, QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)); testLocations.insert(QStandardPaths::ConfigLocation, QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)); + testLocations.insert(QStandardPaths::GenericConfigLocation, QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)); testLocations.insert(QStandardPaths::CacheLocation, QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); testLocations.insert(QStandardPaths::GenericCacheLocation, QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation)); // On Windows, what should "Program Files" become, in test mode? diff --git a/tests/auto/corelib/io/qurl/tst_qurl.cpp b/tests/auto/corelib/io/qurl/tst_qurl.cpp index 2128d68485..12b9159bf2 100644 --- a/tests/auto/corelib/io/qurl/tst_qurl.cpp +++ b/tests/auto/corelib/io/qurl/tst_qurl.cpp @@ -378,6 +378,14 @@ void tst_QUrl::comparison() QVERIFY(!passUrl1.matches(passUrl2, QUrl::None)); QVERIFY(passUrl1.matches(passUrl2, QUrl::RemovePassword)); + // RemovePassword, null vs empty + QUrl emptyPassUrl1("http://user:@host/"); + QUrl emptyPassUrl2("http://user@host/"); + QVERIFY(!(emptyPassUrl1 == emptyPassUrl2)); + QVERIFY(emptyPassUrl1 != emptyPassUrl2); + QVERIFY(!emptyPassUrl1.matches(emptyPassUrl2, QUrl::None)); + QVERIFY(emptyPassUrl1.matches(emptyPassUrl2, QUrl::RemovePassword)); + // RemoveQuery, RemoveFragment QUrl queryFragUrl1("http://host/file?query#fragment"); QUrl queryFragUrl2("http://host/file?q2#f2"); diff --git a/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp b/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp index 870e65f0cc..3afc2bc574 100644 --- a/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp +++ b/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp @@ -155,6 +155,7 @@ private slots: void invokeCustomTypes(); void invokeMetaConstructor(); void invokeTypedefTypes(); + void invokeException(); void qtMetaObjectInheritance(); void normalizedSignature_data(); void normalizedSignature(); @@ -301,6 +302,19 @@ void tst_QMetaObject::connectSlotsByName() struct MyUnregisteredType { }; +static int countedStructObjectsCount = 0; +struct CountedStruct +{ + CountedStruct() { ++countedStructObjectsCount; } + CountedStruct(const CountedStruct &) { ++countedStructObjectsCount; } + CountedStruct &operator=(const CountedStruct &) { return *this; } + ~CountedStruct() { --countedStructObjectsCount; } +}; + +#ifndef QT_NO_EXCEPTIONS +class ObjectException : public std::exception { }; +#endif + class QtTestObject: public QObject { friend class tst_QMetaObject; @@ -340,6 +354,13 @@ public slots: void slotWithUnregisteredParameterType(MyUnregisteredType); + CountedStruct throwingSlot(const CountedStruct &, CountedStruct s2) { +#ifndef QT_NO_EXCEPTIONS + throw ObjectException(); +#endif + return s2; + } + signals: void sig0(); QString sig1(QString s1); @@ -847,6 +868,23 @@ void tst_QMetaObject::invokeTypedefTypes() QCOMPARE(spy.at(0).at(0), QVariant(arg)); } +void tst_QMetaObject::invokeException() +{ +#ifndef QT_NO_EXCEPTIONS + QtTestObject obj; + QCOMPARE(countedStructObjectsCount, 0); + try { + CountedStruct s; + QVERIFY(QMetaObject::invokeMethod(&obj, "throwingSlot", Q_RETURN_ARG(CountedStruct, s), + Q_ARG(CountedStruct, s), Q_ARG(CountedStruct, s))); + QFAIL("Did not throw"); + } catch(ObjectException &) {} + QCOMPARE(countedStructObjectsCount, 0); +#else + QSKIP("Needs exceptions"); +#endif +} + void tst_QMetaObject::normalizedSignature_data() { QTest::addColumn<QString>("signature"); diff --git a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp index f429500077..e4804e6079 100644 --- a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp +++ b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp @@ -152,6 +152,7 @@ private slots: void contextDoesNotLeakFunctor(); void connectBase(); void qmlConnect(); + void exceptions(); }; struct QObjectCreatedOnShutdown @@ -6185,6 +6186,102 @@ void tst_QObject::qmlConnect() #endif } +#ifndef QT_NO_EXCEPTIONS +class ObjectException : public std::exception { }; + +struct ThrowFunctor +{ + CountedStruct operator()(const CountedStruct &, CountedStruct s2) const + { + throw ObjectException(); + return s2; + } + CountedStruct s; +}; +#endif + +class ExceptionThrower : public QObject +{ + Q_OBJECT +public slots: + CountedStruct throwException(const CountedStruct &, CountedStruct s2) + { +#ifndef QT_NO_EXCEPTIONS + throw ObjectException(); +#endif + return s2; + } +signals: + CountedStruct mySignal(const CountedStruct &s1, CountedStruct s2); +}; + +void tst_QObject::exceptions() +{ +#ifndef QT_NO_EXCEPTIONS + ReceiverObject receiver; + + // String based syntax + { + QCOMPARE(countedStructObjectsCount, 0); + ExceptionThrower thrower; + receiver.reset(); + + connect(&thrower, SIGNAL(mySignal(CountedStruct,CountedStruct)), &receiver, SLOT(slot1())); + connect(&thrower, SIGNAL(mySignal(CountedStruct,CountedStruct)), &thrower, SLOT(throwException(CountedStruct,CountedStruct))); + connect(&thrower, SIGNAL(mySignal(CountedStruct,CountedStruct)), &receiver, SLOT(slot2())); + try { + CountedStruct s; + emit thrower.mySignal(s, s); + QFAIL("Exception not thrown?"); + } catch (ObjectException&) {} + QCOMPARE(receiver.count_slot1, 1); + QCOMPARE(receiver.count_slot2, 0); + QCOMPARE(countedStructObjectsCount, 0); + } + // Pointer to member function + { + QCOMPARE(countedStructObjectsCount, 0); + ExceptionThrower thrower; + receiver.reset(); + + connect(&thrower, &ExceptionThrower::mySignal, &receiver, &ReceiverObject::slot1); + connect(&thrower, &ExceptionThrower::mySignal, &thrower, &ExceptionThrower::throwException); + connect(&thrower, &ExceptionThrower::mySignal, &receiver, &ReceiverObject::slot2); + try { + CountedStruct s; + emit thrower.mySignal(s, s); + QFAIL("Exception not thrown?"); + } catch (ObjectException&) {} + QCOMPARE(receiver.count_slot1, 1); + QCOMPARE(receiver.count_slot2, 0); + QCOMPARE(countedStructObjectsCount, 0); + } + // Functor + { + QCOMPARE(countedStructObjectsCount, 0); + ExceptionThrower thrower; + receiver.reset(); + + connect(&thrower, &ExceptionThrower::mySignal, &receiver, &ReceiverObject::slot1); + connect(&thrower, &ExceptionThrower::mySignal, ThrowFunctor()); + connect(&thrower, &ExceptionThrower::mySignal, &receiver, &ReceiverObject::slot2); + try { + CountedStruct s; + emit thrower.mySignal(s, s); + QFAIL("Exception not thrown?"); + } catch (ObjectException&) {} + QCOMPARE(receiver.count_slot1, 1); + QCOMPARE(receiver.count_slot2, 0); + QCOMPARE(countedStructObjectsCount, 1); // the Functor + } + QCOMPARE(countedStructObjectsCount, 0); + + +#else + QSKIP("Needs exceptions"); +#endif +} + // Test for QtPrivate::HasQ_OBJECT_Macro Q_STATIC_ASSERT(QtPrivate::HasQ_OBJECT_Macro<tst_QObject>::Value); Q_STATIC_ASSERT(!QtPrivate::HasQ_OBJECT_Macro<SiblingDeleter>::Value); diff --git a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp index 422bd63163..aef79e0c2f 100644 --- a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp +++ b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp @@ -247,6 +247,8 @@ private slots: void iterateContainerElements(); void pairElements(); + + void enums(); private: void dataStream_data(QDataStream::Version version); void loadQVariantFromDataStream(QDataStream::Version version); @@ -888,6 +890,17 @@ void tst_QVariant::toLongLong_data() bytearray[3] = '0'; QTest::newRow( "QByteArray" ) << QVariant( bytearray ) << (qlonglong) 3200 << true; QTest::newRow("QJsonValue") << QVariant(QJsonValue(321)) << (qlonglong)321 << true; + + qint64 value64 = (Q_INT64_C(12) << 35) + 8; + QTest::newRow("qint64") << QVariant::fromValue(value64) << qlonglong(value64) << true; + QTest::newRow("-qint64") << QVariant::fromValue(-value64) << qlonglong(-value64) << true; + QTest::newRow("long") << QVariant::fromValue(long(464646)) << qlonglong(464646) << true; + QTest::newRow("LONG_MAX") << QVariant::fromValue( LONG_MAX ) << qlonglong(LONG_MAX) << true; + QTest::newRow("LONG_MIN") << QVariant::fromValue( LONG_MIN ) << qlonglong(LONG_MIN) << true; + + QTest::newRow( "short" ) << QVariant(short(12)) << qlonglong(12) << true; + QTest::newRow( "-short" ) << QVariant(short(-24)) << qlonglong(-24) << true; + QTest::newRow( "ushort" ) << QVariant(ushort(15)) << qlonglong(15) << true; } void tst_QVariant::toLongLong() @@ -933,6 +946,15 @@ void tst_QVariant::toULongLong_data() bytearray[3] = '1'; QTest::newRow( "QByteArray" ) << QVariant( bytearray ) << (qulonglong) 3201 << true; QTest::newRow("QJsonValue") << QVariant(QJsonValue(321)) << (qulonglong)321 << true; + + quint64 value64 = (Q_INT64_C(12) << 35) + 8; + QTest::newRow("qint64") << QVariant::fromValue(value64) << qulonglong(value64) << true; + QTest::newRow("long") << QVariant::fromValue(long(464646)) << qulonglong(464646) << true; + QTest::newRow("LONG_MAX") << QVariant::fromValue( LONG_MAX ) << qulonglong(LONG_MAX) << true; + QTest::newRow("ULONG_MAX") << QVariant::fromValue( ULONG_MAX ) << qulonglong(ULONG_MAX) << true; + QTest::newRow( "short" ) << QVariant(short(12)) << qulonglong(12) << true; + QTest::newRow( "-short" ) << QVariant(short(-24)) << qulonglong(-24) << true; + QTest::newRow( "ushort" ) << QVariant(ushort(15)) << qulonglong(15) << true; } void tst_QVariant::toULongLong() @@ -2895,24 +2917,27 @@ void tst_QVariant::numericalConvert() QVariant vuint(uint(5)); QVariant vshort(short(5)); QVariant vlonglong(quint64(5)); + QVariant vlong = QVariant::fromValue(long(5)); QVariant vstringint(QString::fromLatin1("5")); QVariant vstring(QString::fromLatin1("5.3")); QVector<QVariant *> vect; - vect << &vfloat << &vdouble << &vreal << &vint << &vuint << &vshort<< &vlonglong << &vstringint << &vstring; + vect << &vfloat << &vdouble << &vreal << &vint << &vuint << &vshort<< &vlonglong << &vlong << &vstringint << &vstring; for(int i = 0; i < vect.size(); i++) { double num = 5.3; - if (i >= 3 && i <= 7) + if (i >= 3 && i <= 8) num = 5; QVariant *v = vect.at(i); QCOMPARE(v->toFloat() , float(num)); QCOMPARE(float(v->toReal()) , float(num)); QCOMPARE(float(v->toDouble()) , float(num)); - if(i != 8) { + if (i != 9) { QCOMPARE(v->toInt() , int(num)); QCOMPARE(v->toUInt() , uint(num)); QCOMPARE(v->toULongLong() , quint64(num)); + QCOMPARE(v->value<ulong>() , ulong(num)); + QCOMPARE(v->value<ushort>() , ushort(num)); } QCOMPARE(v->toString() , QString::number(num)); } @@ -3930,5 +3955,87 @@ void tst_QVariant::pairElements() TEST_PAIR_ELEMENT_ACCESS(std::pair, int, QVariant, 44, 15) } +enum EnumTest_Enum0 { EnumTest_Enum0_value = 42, ensureSignedEnum0 = -1 }; +Q_DECLARE_METATYPE(EnumTest_Enum0) +enum EnumTest_Enum1 { EnumTest_Enum1_value = 42, EnumTest_Enum1_bigValue = (Q_INT64_C(1) << 33) + 50 }; +Q_DECLARE_METATYPE(EnumTest_Enum1) + +#if defined(Q_COMPILER_CLASS_ENUM) +enum EnumTest_Enum3 : qint64 { EnumTest_Enum3_value = -47, EnumTest_Enum3_bigValue = (Q_INT64_C(1) << 56) + 5 }; +Q_DECLARE_METATYPE(EnumTest_Enum3) +enum EnumTest_Enum4 : quint64 { EnumTest_Enum4_value = 47, EnumTest_Enum4_bigValue = (Q_INT64_C(1) << 52) + 45 }; +Q_DECLARE_METATYPE(EnumTest_Enum4) +enum EnumTest_Enum5 : uint { EnumTest_Enum5_value = 47 }; +Q_DECLARE_METATYPE(EnumTest_Enum5) +enum EnumTest_Enum6 : uchar { EnumTest_Enum6_value = 47 }; +Q_DECLARE_METATYPE(EnumTest_Enum6) +enum class EnumTest_Enum7 { EnumTest_Enum7_value = 47, ensureSignedEnum7 = -1 }; +Q_DECLARE_METATYPE(EnumTest_Enum7) +enum EnumTest_Enum8 : short { EnumTest_Enum8_value = 47 }; +Q_DECLARE_METATYPE(EnumTest_Enum8) +#endif + +template<typename Enum> void testVariant(Enum value, bool *ok) +{ + *ok = false; + QVariant var = QVariant::fromValue(value); + + QCOMPARE(var.userType(), qMetaTypeId<Enum>()); + + QVERIFY(var.canConvert<Enum>()); + QVERIFY(var.canConvert<int>()); + QVERIFY(var.canConvert<unsigned int>()); + QVERIFY(var.canConvert<short>()); + QVERIFY(var.canConvert<unsigned short>()); + QVERIFY(var.canConvert<qint64>()); + QVERIFY(var.canConvert<quint64>()); + + + QCOMPARE(var.value<Enum>(), value); + QCOMPARE(var.value<int>(), static_cast<int>(value)); + QCOMPARE(var.value<uint>(), static_cast<uint>(value)); + QCOMPARE(var.value<short>(), static_cast<short>(value)); + QCOMPARE(var.value<unsigned short>(), static_cast<unsigned short>(value)); + QCOMPARE(var.value<qint64>(), static_cast<qint64>(value)); + QCOMPARE(var.value<quint64>(), static_cast<quint64>(value)); + + QVariant var2 = var; + QVERIFY(var2.convert(QMetaType::Int)); + QCOMPARE(var2.value<int>(), static_cast<int>(value)); + + *ok = true; +} + +void tst_QVariant::enums() +{ + bool ok = false; + testVariant(EnumTest_Enum0_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum1_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum1_bigValue, &ok); + QVERIFY(ok); +#if defined(Q_COMPILER_CLASS_ENUM) + testVariant(EnumTest_Enum3::EnumTest_Enum3_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum3::EnumTest_Enum3_bigValue, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum4::EnumTest_Enum4_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum4::EnumTest_Enum4_bigValue, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum5::EnumTest_Enum5_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum6::EnumTest_Enum6_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum7::EnumTest_Enum7_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum8::EnumTest_Enum8_value, &ok); + QVERIFY(ok); + testVariant(EnumTest_Enum3::EnumTest_Enum3_value, &ok); + QVERIFY(ok); +#endif +} + QTEST_MAIN(tst_QVariant) #include "tst_qvariant.moc" diff --git a/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp b/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp index 8a0ff162c6..952cb031b8 100644 --- a/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp +++ b/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp @@ -42,6 +42,7 @@ #include <QtTest/QtTest> #include <qwineventnotifier.h> #include <qtimer.h> +#include <qt_windows.h> class tst_QWinEventNotifier : public QObject { diff --git a/tests/auto/corelib/plugin/quuid/tst_quuid.cpp b/tests/auto/corelib/plugin/quuid/tst_quuid.cpp index 197d56359f..227351485d 100644 --- a/tests/auto/corelib/plugin/quuid/tst_quuid.cpp +++ b/tests/auto/corelib/plugin/quuid/tst_quuid.cpp @@ -64,6 +64,7 @@ private slots: void isNull(); void equal(); void notEqual(); + void cpp11(); // Only in Qt > 3.2.x void generate(); @@ -245,6 +246,17 @@ void tst_QUuid::notEqual() QVERIFY( uuidA != uuidB ); } +void tst_QUuid::cpp11() { +#ifdef Q_COMPILER_UNIFORM_INIT + // "{fc69b59e-cc34-4436-a43c-ee95d128b8c5}" cf, initTestCase + Q_DECL_CONSTEXPR QUuid u1{0xfc69b59e, 0xcc34, 0x4436, 0xa4, 0x3c, 0xee, 0x95, 0xd1, 0x28, 0xb8, 0xc5}; + Q_DECL_CONSTEXPR QUuid u2 = {0xfc69b59e, 0xcc34, 0x4436, 0xa4, 0x3c, 0xee, 0x95, 0xd1, 0x28, 0xb8, 0xc5}; + Q_UNUSED(u1); + Q_UNUSED(u2); +#else + QSKIP("This compiler is not in C++11 mode or it doesn't support uniform initialization"); +#endif +} void tst_QUuid::generate() { diff --git a/tests/auto/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp b/tests/auto/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp index 0d51f69559..ac8d433f96 100644 --- a/tests/auto/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp +++ b/tests/auto/corelib/thread/qreadwritelock/tst_qreadwritelock.cpp @@ -49,11 +49,13 @@ #ifdef Q_OS_UNIX #include <unistd.h> #endif -#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE) -#include <windows.h> -#define sleep(X) Sleep(X) -#elif defined(Q_OS_WINRT) -#define sleep(X) WaitForSingleObjectEx(GetCurrentThread(), X, FALSE); +#if defined(Q_OS_WIN) +# include <qt_windows.h> +# ifndef Q_OS_WINRT +# define sleep(X) Sleep(X) +# else +# define sleep(X) WaitForSingleObjectEx(GetCurrentThread(), X, FALSE); +# endif #endif //on solaris, threads that loop on the release bool variable diff --git a/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp b/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp index 144bc62b1b..64eb91b7b6 100644 --- a/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp +++ b/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp @@ -1027,7 +1027,7 @@ void tst_QAlgorithms::binaryFindOnLargeContainer() const } // alternative implementation of qPopulationCount for comparison: -static const uint bitsSetInNibble[] = { +static Q_DECL_CONSTEXPR const uint bitsSetInNibble[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, }; diff --git a/tests/auto/corelib/tools/qcollator/qcollator.pro b/tests/auto/corelib/tools/qcollator/qcollator.pro new file mode 100644 index 0000000000..3c5987ffa0 --- /dev/null +++ b/tests/auto/corelib/tools/qcollator/qcollator.pro @@ -0,0 +1,7 @@ +CONFIG += testcase parallel_test +TARGET = tst_qcollator +QT = core testlib +SOURCES = tst_qcollator.cpp +DEFINES += QT_NO_CAST_TO_ASCII +contains(QT_CONFIG,icu):DEFINES += QT_USE_ICU +DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/corelib/tools/qcollator/tst_qcollator.cpp b/tests/auto/corelib/tools/qcollator/tst_qcollator.cpp new file mode 100644 index 0000000000..3df8422a34 --- /dev/null +++ b/tests/auto/corelib/tools/qcollator/tst_qcollator.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <qlocale.h> +#include <qcollator.h> + +#include <cstring> + +class tst_QCollator : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void moveSemantics(); +}; + +#ifdef Q_COMPILER_RVALUE_REFS +static bool dpointer_is_null(QCollator &c) +{ + char mem[sizeof c]; + using namespace std; + memcpy(mem, &c, sizeof c); + for (size_t i = 0; i < sizeof c; ++i) + if (mem[i]) + return false; + return true; +} +#endif + +void tst_QCollator::moveSemantics() +{ +#ifdef Q_COMPILER_RVALUE_REFS + const QLocale de_AT(QLocale::German, QLocale::Austria); + + QCollator c1(de_AT); + QCOMPARE(c1.locale(), de_AT); + + QCollator c2(std::move(c1)); + QCOMPARE(c2.locale(), de_AT); + QVERIFY(dpointer_is_null(c1)); + + c1 = std::move(c2); + QCOMPARE(c1.locale(), de_AT); + QVERIFY(dpointer_is_null(c2)); +#else + QSKIP("The compiler is not in C++11 mode or does not support move semantics."); +#endif +} + +QTEST_APPLESS_MAIN(tst_QCollator) + +#include "tst_qcollator.moc" diff --git a/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp b/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp index 07f8ddfc8e..2b30b0486b 100644 --- a/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp +++ b/tests/auto/corelib/tools/qcommandlineparser/testhelper/qcommandlineparser_test_helper.cpp @@ -69,9 +69,18 @@ int main(int argc, char *argv[]) // An option with a longer description, to test wrapping QCommandLineOption noImplicitIncludesOption(QStringList() << QStringLiteral("n") << QStringLiteral("no-implicit-includes")); - noImplicitIncludesOption.setDescription(QStringLiteral("Disable automatic generation of implicit #include-directives.")); + noImplicitIncludesOption.setDescription(QStringLiteral("Disable magic generation of implicit #include-directives.")); parser.addOption(noImplicitIncludesOption); + QCommandLineOption newlineOption(QStringList() << QStringLiteral("newline")); + newlineOption.setDescription(QString::fromLatin1("This is an option with a rather long\n" + "description using explicit newline characters " + "(but testing automatic wrapping too). In addition, " + "here, we test breaking after a comma. Testing -option. " + "Long URL: http://qt-project.org/wiki/How_to_create_a_library_with_Qt_and_use_it_in_an_application " + "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")); + parser.addOption(newlineOption); + // This program supports different options depending on the "command" (first argument). // Call parse() to find out the positional arguments. parser.parse(QCoreApplication::arguments()); diff --git a/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp b/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp index 1ee6cacd97..d5b3323506 100644 --- a/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp +++ b/tests/auto/corelib/tools/qcommandlineparser/tst_qcommandlineparser.cpp @@ -459,27 +459,40 @@ void tst_QCommandLineParser::testVersionOption() #endif // !QT_NO_PROCESS } +static const char expectedOptionsHelp[] = + "Options:\n" + " -h, --help Displays this help.\n" + " -v, --version Displays version information.\n" + " --load <url> Load file from URL.\n" + " -o, --output <file> Set output file.\n" + " -D <key=value> Define macro.\n" + " -n, --no-implicit-includes Disable magic generation of implicit\n" + " #include-directives.\n" + " --newline This is an option with a rather long\n" + " description using explicit newline characters (but\n" + " testing automatic wrapping too). In addition,\n" + " here, we test breaking after a comma. Testing\n" + " -option. Long URL:\n" + " http://qt-project.org/wiki/How_to_create_a_library\n" + " _with_Qt_and_use_it_in_an_application\n" + " abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\n" + " yzabcdefghijklmnopqrstuvwxyz\n"; + void tst_QCommandLineParser::testHelpOption_data() { QTest::addColumn<QCommandLineParser::SingleDashWordOptionMode>("parsingMode"); QTest::addColumn<QString>("expectedHelpOutput"); - QString expectedOutput = + QString expectedOutput = QString::fromLatin1( "Usage: testhelper/qcommandlineparser_test_helper [options] parsingMode command\n" "Test helper\n" - "\n" - "Options:\n" - " -h, --help Displays this help.\n" - " -v, --version Displays version information.\n" - " --load <url> Load file from URL.\n" - " -o, --output <file> Set output file.\n" - " -D <key=value> Define macro.\n" - " -n, --no-implicit-includes Disable automatic generation of implicit #include\n" - " -directives.\n" + "\n") + + QString::fromLatin1(expectedOptionsHelp) + + QString::fromLatin1( "\n" "Arguments:\n" " parsingMode The parsing mode to test.\n" - " command The command to execute.\n"; + " command The command to execute.\n"); #ifdef Q_OS_WIN expectedOutput.replace(" -h, --help Displays this help.\n", " -?, -h, --help Displays this help.\n"); @@ -510,6 +523,7 @@ void tst_QCommandLineParser::testHelpOption() #ifdef Q_OS_WIN output.replace(QStringLiteral("\r\n"), QStringLiteral("\n")); #endif + QCOMPARE(output.split('\n'), expectedHelpOutput.split('\n')); // easier to debug than the next line, on failure QCOMPARE(output, expectedHelpOutput); process.start("testhelper/qcommandlineparser_test_helper", QStringList() << "0" << "resize" << "--help"); @@ -519,18 +533,11 @@ void tst_QCommandLineParser::testHelpOption() #ifdef Q_OS_WIN output.replace(QStringLiteral("\r\n"), QStringLiteral("\n")); #endif - QByteArray expectedResizeHelp = + QByteArray expectedResizeHelp = QByteArrayLiteral( "Usage: testhelper/qcommandlineparser_test_helper [options] resize [resize_options]\n" "Test helper\n" - "\n" - "Options:\n" - " -h, --help Displays this help.\n" - " -v, --version Displays version information.\n" - " --load <url> Load file from URL.\n" - " -o, --output <file> Set output file.\n" - " -D <key=value> Define macro.\n" - " -n, --no-implicit-includes Disable automatic generation of implicit #include\n" - " -directives.\n" + "\n") + + expectedOptionsHelp + " --size <size> New size.\n" "\n" "Arguments:\n" diff --git a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp index 8c0f32bb74..7d51696fe3 100644 --- a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp +++ b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp @@ -48,7 +48,7 @@ #include <private/qdatetime_p.h> #ifdef Q_OS_WIN -# include <windows.h> +# include <qt_windows.h> # if defined(Q_OS_WINRT) # define tzset() # endif @@ -2906,6 +2906,12 @@ void tst_QDateTime::timeZones() const // - Test 03:00:00 = 1 hour after tran hourAfterStd = QDateTime(QDate(2013, 10, 27), QTime(3, 0, 0), cet); QCOMPARE(hourAfterStd.toMSecsSinceEpoch(), dstToStdMSecs + 3600000); + + // Test Time Zone that has transitions but no future transitions afer a given date + QTimeZone sgt("Asia/Singapore"); + QDateTime future(QDate(2015, 1, 1), QTime(0, 0, 0), sgt); + QVERIFY(future.isValid()); + QCOMPARE(future.offsetFromUtc(), 28800); } void tst_QDateTime::invalid() const diff --git a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp index f11e632b2e..1bac5f39e7 100644 --- a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp +++ b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp @@ -1733,6 +1733,11 @@ void tst_QLocale::dayName() QLocale ir("ga_IE"); QCOMPARE(ir.dayName(1, QLocale::ShortFormat), QLatin1String("Luan")); QCOMPARE(ir.dayName(7, QLocale::ShortFormat), QLatin1String("Domh")); + + QLocale gr("el_GR"); + QCOMPARE(gr.dayName(2, QLocale::ShortFormat), QString::fromUtf8("\316\244\317\201\316\257")); + QCOMPARE(gr.dayName(4, QLocale::ShortFormat), QString::fromUtf8("\316\240\316\255\316\274")); + QCOMPARE(gr.dayName(6, QLocale::ShortFormat), QString::fromUtf8("\316\243\316\254\316\262")); } void tst_QLocale::standaloneDayName_data() @@ -1903,6 +1908,10 @@ void tst_QLocale::timeFormat() const QLocale cat("ca_ES"); QCOMPARE(cat.timeFormat(QLocale::ShortFormat), QLatin1String("H.mm")); QCOMPARE(cat.timeFormat(QLocale::LongFormat), QLatin1String("H.mm.ss t")); + + const QLocale bra("pt_BR"); + QCOMPARE(bra.timeFormat(QLocale::ShortFormat), QLatin1String("HH:mm")); + QCOMPARE(bra.timeFormat(QLocale::LongFormat), QLatin1String("HH:mm:ss t")); } void tst_QLocale::dateTimeFormat() diff --git a/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp b/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp index 28245b5e6a..0a63ffeeaf 100644 --- a/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp +++ b/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp @@ -57,6 +57,7 @@ private slots: void nullTest(); void dataStreamTest(); void availableTimeZoneIds(); + void stressTest(); void windowsId(); // Backend tests void utcTest(); @@ -75,7 +76,7 @@ private: tst_QTimeZone::tst_QTimeZone() { - // Set to true to print debug output + // Set to true to print debug output, test Display Names and run long stress tests debug = false; } @@ -367,11 +368,59 @@ void tst_QTimeZone::availableTimeZoneIds() } } +void tst_QTimeZone::stressTest() +{ + QList<QByteArray> idList = QTimeZone::availableTimeZoneIds(); + foreach (const QByteArray &id, idList) { + QTimeZone testZone = QTimeZone(id); + QCOMPARE(testZone.isValid(), true); + QCOMPARE(testZone.id(), id); + QDateTime testDate = QDateTime(QDate(2015, 1, 1), QTime(0, 0, 0), Qt::UTC); + testZone.country(); + testZone.comment(); + testZone.displayName(testDate); + testZone.displayName(QTimeZone::DaylightTime); + testZone.displayName(QTimeZone::StandardTime); + testZone.abbreviation(testDate); + testZone.offsetFromUtc(testDate); + testZone.standardTimeOffset(testDate); + testZone.daylightTimeOffset(testDate); + testZone.hasDaylightTime(); + testZone.isDaylightTime(testDate); + testZone.offsetData(testDate); + testZone.hasTransitions(); + testZone.nextTransition(testDate); + testZone.previousTransition(testDate); + // Dates known to be outside possible tz file pre-calculated rules range + QDateTime lowDate1 = QDateTime(QDate(1800, 1, 1), QTime(0, 0, 0), Qt::UTC); + QDateTime lowDate2 = QDateTime(QDate(1800, 6, 1), QTime(0, 0, 0), Qt::UTC); + QDateTime highDate1 = QDateTime(QDate(2200, 1, 1), QTime(0, 0, 0), Qt::UTC); + QDateTime highDate2 = QDateTime(QDate(2200, 6, 1), QTime(0, 0, 0), Qt::UTC); + testZone.nextTransition(lowDate1); + testZone.nextTransition(lowDate2); + testZone.previousTransition(lowDate2); + testZone.previousTransition(lowDate2); + testZone.nextTransition(highDate1); + testZone.nextTransition(highDate2); + testZone.previousTransition(highDate1); + testZone.previousTransition(highDate2); + if (debug) { + // This could take a long time, depending on platform and database + qDebug() << "Stress test calculating transistions for" << testZone.id(); + testZone.transitions(lowDate1, highDate1); + } + testDate.setTimeZone(testZone); + testDate.isValid(); + testDate.offsetFromUtc(); + testDate.timeZoneAbbreviation(); + } +} + void tst_QTimeZone::windowsId() { /* Current Windows zones for "Central Standard Time": - Region Olsen Id(s) + Region IANA Id(s) Default "America/Chicago" Canada "America/Winnipeg America/Rainy_River America/Rankin_Inlet America/Resolute" Mexico "America/Matamoros" @@ -380,24 +429,24 @@ void tst_QTimeZone::windowsId() "America/North_Dakota/New_Salem" AnyCountry "CST6CDT" */ - QCOMPARE(QTimeZone::olsenIdToWindowsId("America/Chicago"), + QCOMPARE(QTimeZone::ianaIdToWindowsId("America/Chicago"), QByteArray("Central Standard Time")); - QCOMPARE(QTimeZone::olsenIdToWindowsId("America/Resolute"), + QCOMPARE(QTimeZone::ianaIdToWindowsId("America/Resolute"), QByteArray("Central Standard Time")); // Partials shouldn't match - QCOMPARE(QTimeZone::olsenIdToWindowsId("America/Chi"), QByteArray()); - QCOMPARE(QTimeZone::olsenIdToWindowsId("InvalidZone"), QByteArray()); - QCOMPARE(QTimeZone::olsenIdToWindowsId(QByteArray()), QByteArray()); + QCOMPARE(QTimeZone::ianaIdToWindowsId("America/Chi"), QByteArray()); + QCOMPARE(QTimeZone::ianaIdToWindowsId("InvalidZone"), QByteArray()); + QCOMPARE(QTimeZone::ianaIdToWindowsId(QByteArray()), QByteArray()); // Check default value - QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId("Central Standard Time"), + QCOMPARE(QTimeZone::windowsIdToDefaultIanaId("Central Standard Time"), QByteArray("America/Chicago")); - QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId("Central Standard Time", QLocale::Canada), + QCOMPARE(QTimeZone::windowsIdToDefaultIanaId("Central Standard Time", QLocale::Canada), QByteArray("America/Winnipeg")); - QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId("Central Standard Time", QLocale::AnyCountry), + QCOMPARE(QTimeZone::windowsIdToDefaultIanaId("Central Standard Time", QLocale::AnyCountry), QByteArray("CST6CDT")); - QCOMPARE(QTimeZone::windowsIdToDefaultOlsenId(QByteArray()), QByteArray()); + QCOMPARE(QTimeZone::windowsIdToDefaultIanaId(QByteArray()), QByteArray()); // No country is sorted list of all zones QList<QByteArray> list; @@ -406,39 +455,39 @@ void tst_QTimeZone::windowsId() << "America/North_Dakota/Center" << "America/North_Dakota/New_Salem" << "America/Rainy_River" << "America/Rankin_Inlet" << "America/Resolute" << "America/Winnipeg" << "CST6CDT"; - QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time"), list); + QCOMPARE(QTimeZone::windowsIdToIanaIds("Central Standard Time"), list); // Check country with no match returns empty list list.clear(); - QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::NewZealand), + QCOMPARE(QTimeZone::windowsIdToIanaIds("Central Standard Time", QLocale::NewZealand), list); // Check valid country returns list in preference order list.clear(); list << "America/Winnipeg" << "America/Rainy_River" << "America/Rankin_Inlet" << "America/Resolute"; - QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::Canada), list); + QCOMPARE(QTimeZone::windowsIdToIanaIds("Central Standard Time", QLocale::Canada), list); list.clear(); list << "America/Matamoros"; - QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::Mexico), list); + QCOMPARE(QTimeZone::windowsIdToIanaIds("Central Standard Time", QLocale::Mexico), list); list.clear(); list << "America/Chicago" << "America/Indiana/Knox" << "America/Indiana/Tell_City" << "America/Menominee" << "America/North_Dakota/Beulah" << "America/North_Dakota/Center" << "America/North_Dakota/New_Salem"; - QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::UnitedStates), + QCOMPARE(QTimeZone::windowsIdToIanaIds("Central Standard Time", QLocale::UnitedStates), list); list.clear(); list << "CST6CDT"; - QCOMPARE(QTimeZone::windowsIdToOlsenIds("Central Standard Time", QLocale::AnyCountry), + QCOMPARE(QTimeZone::windowsIdToIanaIds("Central Standard Time", QLocale::AnyCountry), list); // Check no windowsId return empty list.clear(); - QCOMPARE(QTimeZone::windowsIdToOlsenIds(QByteArray()), list); - QCOMPARE(QTimeZone::windowsIdToOlsenIds(QByteArray(), QLocale::AnyCountry), list); + QCOMPARE(QTimeZone::windowsIdToIanaIds(QByteArray()), list); + QCOMPARE(QTimeZone::windowsIdToIanaIds(QByteArray(), QLocale::AnyCountry), list); } void tst_QTimeZone::utcTest() @@ -639,10 +688,11 @@ void tst_QTimeZone::tzTest() QCOMPARE(dat.standardTimeOffset, 3600); QCOMPARE(dat.daylightTimeOffset, 0); + // Test previous to low value is invalid dat = tzp.previousTransition(-9999999999999); - QCOMPARE(dat.atMSecsSinceEpoch, (qint64)-2422054408000); - QCOMPARE(dat.standardTimeOffset, 3600); - QCOMPARE(dat.daylightTimeOffset, 0); + QCOMPARE(dat.atMSecsSinceEpoch, std::numeric_limits<qint64>::min()); + QCOMPARE(dat.standardTimeOffset, std::numeric_limits<int>::min()); + QCOMPARE(dat.daylightTimeOffset, std::numeric_limits<int>::min()); dat = tzp.nextTransition(-9999999999999); QCOMPARE(dat.atMSecsSinceEpoch, (qint64)-2422054408000); diff --git a/tests/auto/corelib/tools/tools.pro b/tests/auto/corelib/tools/tools.pro index e920813db2..286afdfd18 100644 --- a/tests/auto/corelib/tools/tools.pro +++ b/tests/auto/corelib/tools/tools.pro @@ -8,6 +8,7 @@ SUBDIRS=\ qbytedatabuffer \ qcache \ qchar \ + qcollator \ qcommandlineparser \ qcontiguouscache \ qcryptographichash \ diff --git a/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp b/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp index 1220ce3b23..efc688f0b1 100644 --- a/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp +++ b/tests/auto/gui/kernel/qguivariant/test/tst_qguivariant.cpp @@ -118,6 +118,7 @@ private slots: void colorInteger(); void invalidQColor(); + void validQColor(); void debugStream_data(); void debugStream(); @@ -542,6 +543,21 @@ void tst_QGuiVariant::invalidQColor() QVERIFY(!qvariant_cast<QColor>(va).isValid()); } +void tst_QGuiVariant::validQColor() +{ + QColor col(Qt::red); + QVariant va(col.name()); + QVERIFY(va.canConvert(QVariant::Color)); + + QVERIFY(va.convert(QVariant::Color)); + + QVERIFY(col.isValid()); + + QVERIFY(va.convert(QVariant::String)); + + QCOMPARE(qvariant_cast<QString>(va), col.name()); +} + void tst_QGuiVariant::colorInteger() { QVariant v = QColor(Qt::red); diff --git a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp index c4983f4462..259c840ae7 100644 --- a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp +++ b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp @@ -177,7 +177,7 @@ void tst_QWindow::resizeEventAfterResize() Window window; window.setGeometry(geometry); - window.show(); + window.showNormal(); QTRY_COMPARE(window.received(QEvent::Resize), 1); @@ -843,7 +843,10 @@ void tst_QWindow::activateAndClose() { for (int i = 0; i < 10; ++i) { QWindow window; - window.show(); + // qWaitForWindowActive will block for the duration of + // of the timeout if the window is at 0,0 + window.setGeometry(QGuiApplication::primaryScreen()->availableGeometry().adjusted(1, 1, -1, -1)); + window.showNormal(); window.requestActivate(); QVERIFY(QTest::qWaitForWindowActive(&window)); QCOMPARE(qGuiApp->focusWindow(), &window); diff --git a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp index 1abac3a28a..53aef40df0 100644 --- a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp +++ b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp @@ -187,8 +187,6 @@ private slots: void htmlExportImportBlockCount(); void QTBUG27354_spaceAndSoftSpace(); - void cssInheritance(); - void baseUrl_data(); void baseUrl(); @@ -2952,35 +2950,6 @@ void tst_QTextDocument::QTBUG27354_spaceAndSoftSpace() } } -void tst_QTextDocument::cssInheritance() -{ - { - QTextDocument td; - td.setHtml("<html><head><style type=\"text/css\">body { line-height: 200% }</style></head><body>" - "<p>Foo</p><p>Bar</p><p>Baz</p></body></html>"); - QTextBlock block = td.begin(); - while (block.isValid()) { - QTextBlockFormat fmt = block.blockFormat(); - QVERIFY(fmt.lineHeightType() == QTextBlockFormat::ProportionalHeight); - QVERIFY(fmt.lineHeight() == 200); - block = block.next(); - } - } - { - QTextDocument td; - td.setHtml("<html><head><style type=\"text/css\">body { line-height: 200% } p { line-height: 300% }</style></head><body>" - "<p style=\"line-height: 40px\">Foo</p><p>Bar</p><p>Baz</p></body></html>"); - QTextBlock block = td.begin(); - QTextBlockFormat fmt = block.blockFormat(); - QVERIFY(fmt.lineHeightType() == QTextBlockFormat::FixedHeight); - QVERIFY(fmt.lineHeight() == 40); - block = block.next(); - fmt = block.blockFormat(); - QVERIFY(fmt.lineHeightType() == QTextBlockFormat::ProportionalHeight); - QVERIFY(fmt.lineHeight() == 300); - } -} - class BaseDocument : public QTextDocument { public: diff --git a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp index 2826c497df..1837e8d665 100644 --- a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp +++ b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp @@ -6042,7 +6042,7 @@ void tst_QNetworkReply::sslSessionSharingFromPersistentSession() QTestEventLoop::instance().enterLoop(20); QVERIFY(!QTestEventLoop::instance().timeout()); QCOMPARE(warmupReply->error(), QNetworkReply::NoError); - QByteArray sslSession = warmupReply->sslConfiguration().session(); + QByteArray sslSession = warmupReply->sslConfiguration().sessionTicket(); QCOMPARE(!sslSession.isEmpty(), sessionPersistenceEnabled); // test server sends a life time hint of 0 (old server) or 300 (new server), @@ -6060,7 +6060,7 @@ void tst_QNetworkReply::sslSessionSharingFromPersistentSession() QNetworkRequest request(warmupRequest); if (sessionPersistenceEnabled) { QSslConfiguration configuration = request.sslConfiguration(); - configuration.setSession(sslSession); + configuration.setSessionTicket(sslSession); request.setSslConfiguration(configuration); } QNetworkAccessManager newManager; diff --git a/tests/auto/opengl/qgl/qgl.pro b/tests/auto/opengl/qgl/qgl.pro index 311e41a624..35b5c6888b 100644 --- a/tests/auto/opengl/qgl/qgl.pro +++ b/tests/auto/opengl/qgl/qgl.pro @@ -12,3 +12,4 @@ RESOURCES = qgl.qrc linux-*:system(". /etc/lsb-release && [ $DISTRIB_CODENAME = lucid ]"): CONFIG+=insignificant_test # QTBUG-25293 DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 +win32-msvc2010:contains(QT_CONFIG, angle):CONFIG += insignificant_test # QTQAINFRA-711 diff --git a/tests/auto/opengl/qglthreads/tst_qglthreads.cpp b/tests/auto/opengl/qglthreads/tst_qglthreads.cpp index c74edab9a2..f5923764b8 100644 --- a/tests/auto/opengl/qglthreads/tst_qglthreads.cpp +++ b/tests/auto/opengl/qglthreads/tst_qglthreads.cpp @@ -346,12 +346,12 @@ void renderAScene(int w, int h) for (int i=0; i<1000; ++i) { GLfloat pos[] = { - (rand() % 100) / 100., - (rand() % 100) / 100., - (rand() % 100) / 100., - (rand() % 100) / 100., - (rand() % 100) / 100., - (rand() % 100) / 100. + (rand() % 100) / 100.f, + (rand() % 100) / 100.f, + (rand() % 100) / 100.f, + (rand() % 100) / 100.f, + (rand() % 100) / 100.f, + (rand() % 100) / 100.f }; glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, pos); diff --git a/tests/auto/other/macgui/guitest.cpp b/tests/auto/other/macgui/guitest.cpp index d7431dd88e..3359e7d935 100644 --- a/tests/auto/other/macgui/guitest.cpp +++ b/tests/auto/other/macgui/guitest.cpp @@ -144,22 +144,25 @@ WidgetNavigator::~WidgetNavigator() namespace NativeEvents { #ifdef Q_OS_MAC - void mouseClick(const QPoint &globalPos, Qt::MouseButtons buttons, MousePosition updateMouse) + void mouseClick(const QPoint &globalPos, Qt::MouseButtons buttons) { CGPoint position; position.x = globalPos.x(); position.y = globalPos.y(); - const bool updateMousePosition = (updateMouse == UpdatePosition); - - // Mouse down. - CGPostMouseEvent(position, updateMousePosition, 3, - (buttons & Qt::LeftButton) ? true : false, - (buttons & Qt::MidButton/* Middlebutton! */) ? true : false, - (buttons & Qt::RightButton) ? true : false); - - // Mouse up. - CGPostMouseEvent(position, updateMousePosition, 3, false, false, false); + CGEventType mouseDownType = (buttons & Qt::LeftButton) ? kCGEventLeftMouseDown : + (buttons & Qt::RightButton) ? kCGEventRightMouseDown : + kCGEventOtherMouseDown; + CGMouseButton mouseButton = mouseDownType == kCGEventOtherMouseDown ? kCGMouseButtonCenter : kCGEventLeftMouseDown; + CGEventRef mouseEvent = CGEventCreateMouseEvent(NULL, mouseDownType, position, mouseButton); + CGEventPost(kCGHIDEventTap, mouseEvent); + + CGEventType mouseUpType = (buttons & Qt::LeftButton) ? kCGEventLeftMouseUp : + (buttons & Qt::RightButton) ? kCGEventRightMouseUp : + kCGEventOtherMouseUp; + CGEventSetType(mouseEvent, mouseUpType); + CGEventPost(kCGHIDEventTap, mouseEvent); + CFRelease(mouseEvent); } #else # error Oops, NativeEvents::mouseClick() is not implemented on this platform. diff --git a/tests/auto/other/macgui/guitest.h b/tests/auto/other/macgui/guitest.h index 569a67d7fe..6fc4eac59f 100644 --- a/tests/auto/other/macgui/guitest.h +++ b/tests/auto/other/macgui/guitest.h @@ -86,11 +86,10 @@ private: (Implemented so far: mouseClick on Mac) */ namespace NativeEvents { - enum MousePosition { UpdatePosition, DontUpdatePosition }; /* Simulates a mouse click with button at globalPos. */ - void mouseClick(const QPoint &globalPos, Qt::MouseButtons buttons, MousePosition updateMouse = DontUpdatePosition); + void mouseClick(const QPoint &globalPos, Qt::MouseButtons buttons); }; class ColorWidget : public QWidget diff --git a/tests/auto/other/qobjectrace/tst_qobjectrace.cpp b/tests/auto/other/qobjectrace/tst_qobjectrace.cpp index ab05c64fe5..71a90e83f7 100644 --- a/tests/auto/other/qobjectrace/tst_qobjectrace.cpp +++ b/tests/auto/other/qobjectrace/tst_qobjectrace.cpp @@ -47,6 +47,12 @@ enum { OneMinute = 60 * 1000, TwoMinutes = OneMinute * 2 }; + +struct Functor +{ + void operator()() const {}; +}; + class tst_QObjectRace: public QObject { Q_OBJECT @@ -122,11 +128,7 @@ signals: private slots: void checkStopWatch() { -#if defined(Q_OS_WINCE) || defined(Q_OS_VXWORKS) - if (stopWatch.elapsed() >= OneMinute / 2) -#else - if (stopWatch.elapsed() >= OneMinute) -#endif + if (stopWatch.elapsed() >= 5000) quit(); QObject o; @@ -188,16 +190,34 @@ class MyObject : public QObject void signal7(); }; +namespace { +const char *_slots[] = { SLOT(slot1()) , SLOT(slot2()) , SLOT(slot3()), + SLOT(slot4()) , SLOT(slot5()) , SLOT(slot6()), + SLOT(slot7()) }; + +const char *_signals[] = { SIGNAL(signal1()), SIGNAL(signal2()), SIGNAL(signal3()), + SIGNAL(signal4()), SIGNAL(signal5()), SIGNAL(signal6()), + SIGNAL(signal7()) }; +typedef void (MyObject::*PMFType)(); +const PMFType _slotsPMF[] = { &MyObject::slot1, &MyObject::slot2, &MyObject::slot3, + &MyObject::slot4, &MyObject::slot5, &MyObject::slot6, + &MyObject::slot7 }; + +const PMFType _signalsPMF[] = { &MyObject::signal1, &MyObject::signal2, &MyObject::signal3, + &MyObject::signal4, &MyObject::signal5, &MyObject::signal6, + &MyObject::signal7 }; + +} class DestroyThread : public QThread { Q_OBJECT - QObject **objects; + MyObject **objects; int number; public: - void setObjects(QObject **o, int n) + void setObjects(MyObject **o, int n) { objects = o; number = n; @@ -206,8 +226,29 @@ public: } void run() { - for(int i = 0; i < number; i++) + for (int i = number-1; i >= 0; --i) { + /* Do some more connection and disconnection between object in this thread that have not been destroyed yet */ + + const int nAlive = i+1; + connect (objects[((i+1)*31) % nAlive], _signals[(12*i)%7], objects[((i+2)*37) % nAlive], _slots[(15*i+2)%7] ); + disconnect(objects[((i+1)*31) % nAlive], _signals[(12*i)%7], objects[((i+2)*37) % nAlive], _slots[(15*i+2)%7] ); + + connect (objects[((i+4)*41) % nAlive], _signalsPMF[(18*i)%7], objects[((i+5)*43) % nAlive], _slotsPMF[(19*i+2)%7] ); + disconnect(objects[((i+4)*41) % nAlive], _signalsPMF[(18*i)%7], objects[((i+5)*43) % nAlive], _slotsPMF[(19*i+2)%7] ); + + QMetaObject::Connection c = connect(objects[((i+5)*43) % nAlive], _signalsPMF[(9*i+1)%7], Functor()); + disconnect(c); + + disconnect(objects[i], _signalsPMF[(10*i+5)%7], 0, 0); + disconnect(objects[i], _signals[(11*i+6)%7], 0, 0); + + disconnect(objects[i], 0, objects[(i*17+6) % nAlive], 0); + if (i%4 == 1) { + disconnect(objects[i], 0, 0, 0); + } + delete objects[i]; + } } }; @@ -216,27 +257,24 @@ public: void tst_QObjectRace::destroyRace() { - enum { ThreadCount = 10, ObjectCountPerThread = 733, + enum { ThreadCount = 10, ObjectCountPerThread = 2777, ObjectCount = ThreadCount * ObjectCountPerThread }; - const char *_slots[] = { SLOT(slot1()) , SLOT(slot2()) , SLOT(slot3()), - SLOT(slot4()) , SLOT(slot5()) , SLOT(slot6()), - SLOT(slot7()) }; - - const char *_signals[] = { SIGNAL(signal1()), SIGNAL(signal2()), SIGNAL(signal3()), - SIGNAL(signal4()), SIGNAL(signal5()), SIGNAL(signal6()), - SIGNAL(signal7()) }; - - QObject *objects[ObjectCount]; + MyObject *objects[ObjectCount]; for (int i = 0; i < ObjectCount; ++i) objects[i] = new MyObject; - for (int i = 0; i < ObjectCount * 11; ++i) { + for (int i = 0; i < ObjectCount * 17; ++i) { connect(objects[(i*13) % ObjectCount], _signals[(2*i)%7], objects[((i+2)*17) % ObjectCount], _slots[(3*i+2)%7] ); connect(objects[((i+6)*23) % ObjectCount], _signals[(5*i+4)%7], objects[((i+8)*41) % ObjectCount], _slots[(i+6)%7] ); + + connect(objects[(i*67) % ObjectCount], _signalsPMF[(2*i)%7], + objects[((i+1)*71) % ObjectCount], _slotsPMF[(3*i+2)%7] ); + connect(objects[((i+3)*73) % ObjectCount], _signalsPMF[(5*i+4)%7], + objects[((i+5)*79) % ObjectCount], Functor() ); } DestroyThread *threads[ThreadCount]; diff --git a/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp b/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp index 7251cca528..644cd33e5c 100644 --- a/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp +++ b/tests/auto/printsupport/kernel/qprinter/tst_qprinter.cpp @@ -113,6 +113,8 @@ private slots: void testCustomPageSizes(); void customPaperSizeAndMargins_data(); void customPaperSizeAndMargins(); + void customPaperNameSettingBySize(); + void customPaperNameSettingByName(); #if !defined(QT_NO_COMPLETER) && !defined(QT_NO_FILEDIALOG) void printDialogCompleter(); #endif @@ -967,6 +969,13 @@ void tst_QPrinter::errorReporting() painter.end(); } +static QByteArray msgSizeMismatch(const QSizeF &actual, const QSizeF &expected) +{ + QString result; + QDebug(&result) << "Paper size mismatch" << actual << "!=" << expected; + return result.toLocal8Bit(); +} + void tst_QPrinter::testCustomPageSizes() { QPrinter p; @@ -975,12 +984,16 @@ void tst_QPrinter::testCustomPageSizes() p.setPaperSize(customSize, QPrinter::Inch); QSizeF paperSize = p.paperSize(QPrinter::Inch); - QCOMPARE(paperSize, customSize); + // Due to the different calculations, the sizes may be off by a fraction so we have to check it manually + // instead of relying on QSizeF comparison + QVERIFY2(sqrt(pow(paperSize.width() - customSize.width(), 2.0) + pow(paperSize.height() - customSize.height(), 2.0)) < 0.01, + msgSizeMismatch(paperSize, customSize)); QPrinter p2(QPrinter::HighResolution); p2.setPaperSize(customSize, QPrinter::Inch); paperSize = p.paperSize(QPrinter::Inch); - QCOMPARE(paperSize, customSize); + QVERIFY2(sqrt(pow(paperSize.width() - customSize.width(), 2.0) + pow(paperSize.height() - customSize.height(), 2.0)) < 0.01, + msgSizeMismatch(paperSize, customSize)); } void tst_QPrinter::customPaperSizeAndMargins_data() @@ -1193,6 +1206,68 @@ void tst_QPrinter::testPageMetrics() QCOMPARE(printer.pageSizeMM(), QSizeF(widthMMf, heightMMf)); } +void tst_QPrinter::customPaperNameSettingBySize() +{ +#ifndef Q_OS_WIN + QSKIP("Currently this triggers a problem on non Windows platforms, this will be fixed separately - QTBUG-34521"); +#endif + QPrinter printer(QPrinter::HighResolution); + QPrinterInfo info(printer); + QList<QPair<QString, QSizeF> > sizes = info.supportedSizesWithNames(); + if (sizes.size() == 0) + QSKIP("No printers installed on this machine"); + for (int i=0; i<sizes.size(); i++) { + printer.setPaperSize(sizes.at(i).second, QPrinter::Millimeter); + QCOMPARE(sizes.at(i).second, printer.paperSize(QPrinter::Millimeter)); + // Some printers have the same size under different names which can cause a problem for the test + // So we iterate up to the current position to check + QSizeF paperSize = sizes.at(i).second; + QString paperName = printer.paperName(); + bool paperNameFound = (sizes.at(i).first == paperName); + if (!paperNameFound) { + for (int j=0; j<i; j++) { + if (sizes.at(j).second == paperSize && sizes.at(j).first == paperName) { + paperNameFound = true; + break; + } + } + } + // Fail with the original values + if (!paperNameFound) + QCOMPARE(sizes.at(i).first, printer.paperName()); + } + + // Check setting a custom size after setting a standard one works + QSizeF customSize(200, 200); + printer.setPaperSize(customSize, QPrinter::Millimeter); + QCOMPARE(printer.paperSize(QPrinter::Millimeter), customSize); + QCOMPARE(printer.paperSize(), QPrinter::Custom); + + // Finally check setting a standard size after a custom one works + printer.setPaperSize(sizes.at(0).second, QPrinter::Millimeter); + QCOMPARE(printer.paperName(), sizes.at(0).first); + QCOMPARE(printer.paperSize(QPrinter::Millimeter), sizes.at(0).second); +} + +void tst_QPrinter::customPaperNameSettingByName() +{ +#ifndef Q_OS_WIN + QSKIP("Currently this triggers a problem on non Windows platforms, this will be fixed separately - QTBUG-34521"); +#endif + QPrinter printer(QPrinter::HighResolution); + QPrinterInfo info(printer); + QList<QPair<QString, QSizeF> > sizes = info.supportedSizesWithNames(); + if (sizes.size() == 0) + QSKIP("No printers installed on this machine"); + for (int i=0; i<sizes.size(); i++) { + printer.setPaperName(sizes.at(i).first); + QCOMPARE(sizes.at(i).first, printer.paperName()); + QSizeF paperSize = printer.paperSize(QPrinter::Millimeter); + QVERIFY2(sqrt(pow(sizes.at(i).second.width() - paperSize.width(), 2.0) + pow(sizes.at(i).second.height() - paperSize.height(), 2.0)) < 0.01, + msgSizeMismatch(sizes.at(i).second, paperSize)); + } +} + #endif // QT_NO_PRINTER QTEST_MAIN(tst_QPrinter) diff --git a/tests/auto/printsupport/kernel/qprinterinfo/tst_qprinterinfo.cpp b/tests/auto/printsupport/kernel/qprinterinfo/tst_qprinterinfo.cpp index 7deb31c2c9..9416224440 100644 --- a/tests/auto/printsupport/kernel/qprinterinfo/tst_qprinterinfo.cpp +++ b/tests/auto/printsupport/kernel/qprinterinfo/tst_qprinterinfo.cpp @@ -275,6 +275,9 @@ void tst_QPrinterInfo::testConstructors() QCOMPARE(null.printerName(), QString()); QVERIFY(null.isNull()); + QPrinterInfo null2(null); + QVERIFY(null2.isNull()); + QList<QPrinterInfo> printers = QPrinterInfo::availablePrinters(); for (int i = 0; i < printers.size(); ++i) { @@ -295,6 +298,12 @@ void tst_QPrinterInfo::testConstructors() void tst_QPrinterInfo::testAssignment() { + QPrinterInfo null; + QVERIFY(null.isNull()); + QPrinterInfo null2; + null2 = null; + QVERIFY(null2.isNull()); + QList<QPrinterInfo> printers = QPrinterInfo::availablePrinters(); for (int i = 0; i < printers.size(); ++i) { diff --git a/tests/auto/testlib/selftests/tst_selftests.cpp b/tests/auto/testlib/selftests/tst_selftests.cpp index d77e372983..1a8e336b55 100644 --- a/tests/auto/testlib/selftests/tst_selftests.cpp +++ b/tests/auto/testlib/selftests/tst_selftests.cpp @@ -63,7 +63,7 @@ private slots: void cleanup(); private: - void doRunSubTest(QString const& subdir, QStringList const& loggers, QStringList const& arguments); + void doRunSubTest(QString const& subdir, QStringList const& loggers, QStringList const& arguments, bool crashes); QString logName(const QString &logger) const; QList<LoggerSet> allLoggerSets() const; @@ -324,6 +324,7 @@ void tst_Selftests::runSubTest_data() QTest::addColumn<QString>("subdir"); QTest::addColumn<QStringList>("loggers"); QTest::addColumn<QStringList>("arguments"); + QTest::addColumn<bool>("crashes"); QStringList tests = QStringList() // << "alive" // timer dependent @@ -483,11 +484,14 @@ void tst_Selftests::runSubTest_data() continue; } } - + const bool crashes = subtest == QLatin1String("assert") || subtest == QLatin1String("exceptionthrow") + || subtest == QLatin1String("fetchbogus") || subtest == QLatin1String("crashedterminate") + || subtest == QLatin1String("crashes") || subtest == QLatin1String("silent"); QTest::newRow(qPrintable(QString("%1 %2").arg(subtest).arg(loggerSet.name))) << subtest << loggers << arguments + << crashes ; } } @@ -495,30 +499,41 @@ void tst_Selftests::runSubTest_data() #ifndef QT_NO_PROCESS -static void insertEnvironmentVariable(QString const& name, QProcessEnvironment &result) -{ - const QProcessEnvironment systemEnvironment = QProcessEnvironment::systemEnvironment(); - const QString value = systemEnvironment.value(name); - if (!value.isEmpty()) - result.insert(name, value); -} - -static inline QProcessEnvironment processEnvironment() +static QProcessEnvironment processEnvironment() { - QProcessEnvironment result; - insertEnvironmentVariable(QStringLiteral("PATH"), result); - // Preserve DISPLAY for X11 as some tests use Qt GUI. -#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) - insertEnvironmentVariable(QStringLiteral("DISPLAY"), result); -#endif - insertEnvironmentVariable(QStringLiteral("QT_QPA_PLATFORM"), result); + static QProcessEnvironment result; + if (result.isEmpty()) { + const QProcessEnvironment systemEnvironment = QProcessEnvironment::systemEnvironment(); + foreach (const QString &key, systemEnvironment.keys()) { + const bool useVariable = key == QLatin1String("PATH") || key == QLatin1String("QT_QPA_PLATFORM") +#ifdef Q_OS_UNIX + || key == QLatin1String("HOME") || key == QLatin1String("USER") // Required for X11 on openSUSE +# ifndef Q_OS_MAC + || key == QLatin1String("DISPLAY") || key == QLatin1String("XAUTHLOCALHOSTNAME") + || key.startsWith(QLatin1String("XDG_")) +# endif // !Q_OS_MAC +#endif // Q_OS_UNIX #ifdef __COVERAGESCANNER__ - insertEnvironmentVariable(QStringLiteral("QT_TESTCOCOON_ACTIVE"), result); + || key == QLatin1String("QT_TESTCOCOON_ACTIVE") #endif + ; + if (useVariable) + result.insert(key, systemEnvironment.value(key)); + } + } return result; } -void tst_Selftests::doRunSubTest(QString const& subdir, QStringList const& loggers, QStringList const& arguments) +static inline QByteArray msgProcessError(const QString &binary, const QStringList &args, + const QProcessEnvironment &e, const QString &what) +{ + QString result; + QTextStream(&result) <<"Error running " << binary << ' ' << args.join(' ') + << " with environment " << e.toStringList().join(' ') << ": " << what; + return result.toLocal8Bit(); +} + +void tst_Selftests::doRunSubTest(QString const& subdir, QStringList const& loggers, QStringList const& arguments, bool crashes) { #if defined(__GNUC__) && defined(__i386) && defined(Q_OS_LINUX) if (arguments.contains("-callgrind")) { @@ -536,8 +551,14 @@ void tst_Selftests::doRunSubTest(QString const& subdir, QStringList const& logge proc.setProcessEnvironment(environment); const QString path = subdir + QLatin1Char('/') + subdir; proc.start(path, arguments); - QVERIFY2(proc.waitForStarted(), qPrintable(QString::fromLatin1("Cannot start '%1': %2").arg(path, proc.errorString()))); - QVERIFY2(proc.waitForFinished(), qPrintable(proc.errorString())); + QVERIFY2(proc.waitForStarted(), msgProcessError(path, arguments, environment, QStringLiteral("Cannot start: ") + proc.errorString())); + QVERIFY2(proc.waitForFinished(), msgProcessError(path, arguments, environment, QStringLiteral("Timed out: ") + proc.errorString())); + if (!crashes) { + QVERIFY2(proc.exitStatus() == QProcess::NormalExit, + msgProcessError(path, arguments, environment, + QStringLiteral("Crashed: ") + proc.errorString() + + QStringLiteral(": ") + QString::fromLocal8Bit(proc.readAllStandardError()))); + } QList<QByteArray> actualOutputs; for (int i = 0; i < loggers.count(); ++i) { @@ -704,8 +725,9 @@ void tst_Selftests::runSubTest() QFETCH(QString, subdir); QFETCH(QStringList, loggers); QFETCH(QStringList, arguments); + QFETCH(bool, crashes); - doRunSubTest(subdir, loggers, arguments); + doRunSubTest(subdir, loggers, arguments, crashes); #endif // !QT_NO_PROCESS } diff --git a/tests/auto/tools/moc/moc.pro b/tests/auto/tools/moc/moc.pro index 0d25131c47..779e992881 100644 --- a/tests/auto/tools/moc/moc.pro +++ b/tests/auto/tools/moc/moc.pro @@ -23,7 +23,8 @@ HEADERS += using-namespaces.h no-keywords.h task87883.h c-comments.h backslash-n forward-declared-param.h \ parse-defines.h \ function-with-attributes.h \ - plugin_metadata.h + plugin_metadata.h \ + single-quote-digit-separator-n3781.h if(*-g++*|*-icc*|*-clang*|*-llvm):!irix-*:!win32-*: HEADERS += os9-newlines.h win-newlines.h diff --git a/tests/auto/tools/moc/single-quote-digit-separator-n3781.h b/tests/auto/tools/moc/single-quote-digit-separator-n3781.h new file mode 100644 index 0000000000..0b234011d5 --- /dev/null +++ b/tests/auto/tools/moc/single-quote-digit-separator-n3781.h @@ -0,0 +1,58 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtGui module 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QObject> + +class KDAB : public QObject +{ + Q_OBJECT +public: + // C++1y allows use of single quote as a digit separator, useful for large + // numbers. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf + // Ensure that moc does not get confused with this. + enum Salaries { + Steve +#ifdef Q_MOC_RUN + = 1'234'567 +#endif + }; + Q_ENUMS(Salaries) +}; diff --git a/tests/auto/tools/qdbuscpp2xml/test1.h b/tests/auto/tools/qdbuscpp2xml/test1.h index d4a7d1dab3..b08115e193 100644 --- a/tests/auto/tools/qdbuscpp2xml/test1.h +++ b/tests/auto/tools/qdbuscpp2xml/test1.h @@ -54,7 +54,18 @@ class Test1 : public QObject Q_CLASSINFO("D-Bus Interface", "org.qtProject.qdbuscpp2xmlTests.Test1") Q_PROPERTY(int numProperty1 READ numProperty1 CONSTANT) Q_PROPERTY(int numProperty2 READ numProperty2 WRITE setNumProperty2) + Q_ENUMS(Salaries) public: + // C++1y allows use of single quote as a digit separator, useful for large + // numbers. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf + // Ensure that qdbuscpp2xml does not get confused with this appearing. + enum Salaries { + Steve +#ifdef Q_MOC_RUN + = 1'234'567 +#endif + }; + Test1(QObject *parent = 0) : QObject(parent) {} int numProperty1() { return 42; } diff --git a/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp b/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp index 816d375b97..3a1f650351 100644 --- a/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp +++ b/tests/auto/widgets/dialogs/qfilesystemmodel/tst_qfilesystemmodel.cpp @@ -212,7 +212,14 @@ void tst_QFileSystemModel::rootPath() QString oldRootPath = model->rootPath(); const QStringList documentPaths = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation); QVERIFY(!documentPaths.isEmpty()); - const QString documentPath = documentPaths.front(); + QString documentPath = documentPaths.front(); + // In particular on Linux, ~/Documents (the first + // DocumentsLocation) may not exist, so choose ~ in that case: + if (!QFile::exists(documentPath)) { + documentPath = QDir::homePath(); + qWarning("%s: first documentPath \"%s\" does not exist. Using ~ (\"%s\") instead.", + Q_FUNC_INFO, qPrintable(documentPaths.front()), qPrintable(documentPath)); + } root = model->setRootPath(documentPath); QTRY_VERIFY(model->rowCount(root) >= 0); diff --git a/tests/auto/widgets/dialogs/qprogressdialog/tst_qprogressdialog.cpp b/tests/auto/widgets/dialogs/qprogressdialog/tst_qprogressdialog.cpp index 68502f0d8d..060fa51293 100644 --- a/tests/auto/widgets/dialogs/qprogressdialog/tst_qprogressdialog.cpp +++ b/tests/auto/widgets/dialogs/qprogressdialog/tst_qprogressdialog.cpp @@ -57,6 +57,8 @@ public: virtual ~tst_QProgressDialog(); private slots: + void autoShow_data(); + void autoShow(); void getSetCheck(); void task198202(); void QTBUG_31046(); @@ -70,6 +72,34 @@ tst_QProgressDialog::~tst_QProgressDialog() { } +void tst_QProgressDialog::autoShow_data() +{ + QTest::addColumn<int>("min"); + QTest::addColumn<int>("max"); + QTest::addColumn<int>("delay"); + QTest::addColumn<bool>("expectedAutoShow"); + + QTest::newRow("50_to_100_long") << 50 << 100 << 100 << true; // 50*100ms = 5s + QTest::newRow("50_to_100_short") << 50 << 1 << 100 << false; // 50*1ms = 50ms + + QTest::newRow("0_to_100_long") << 0 << 100 << 100 << true; // 100*100ms = 10s + QTest::newRow("0_to_10_short") << 0 << 10 << 100 << false; // 10*100ms = 1s +} + +void tst_QProgressDialog::autoShow() +{ + QFETCH(int, min); + QFETCH(int, max); + QFETCH(int, delay); + QFETCH(bool, expectedAutoShow); + + QProgressDialog dlg("", "", min, max); + dlg.setValue(0); + QThread::msleep(delay); + dlg.setValue(min+1); + QCOMPARE(dlg.isVisible(), expectedAutoShow); +} + // Testing get/set functions void tst_QProgressDialog::getSetCheck() { diff --git a/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp b/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp index 4506d0af14..a711bc28e3 100644 --- a/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp +++ b/tests/auto/widgets/dialogs/qwizard/tst_qwizard.cpp @@ -52,6 +52,8 @@ #include <QWizard> #include <QTreeWidget> +Q_DECLARE_METATYPE(QWizard::WizardButton); + static QImage grabWidget(QWidget *window) { return window->grab().toImage(); @@ -100,6 +102,8 @@ private slots: void setWizardStyle(); void removePage(); void sideWidget(); + void objectNames_data(); + void objectNames(); // task-specific tests below me: void task177716_disableCommitButton(); @@ -2384,6 +2388,44 @@ void tst_QWizard::sideWidget() QVERIFY(wizard.sideWidget() == 0); } +void tst_QWizard::objectNames_data() +{ + QTest::addColumn<QWizard::WizardButton>("wizardButton"); + QTest::addColumn<QString>("buttonName"); + + QTest::newRow("BackButton") << QWizard::BackButton << QStringLiteral("__qt__passive_wizardbutton0"); + QTest::newRow("NextButton") << QWizard::NextButton << QStringLiteral("__qt__passive_wizardbutton1"); + QTest::newRow("CommitButton") << QWizard::CommitButton << QStringLiteral("qt_wizard_commit"); + QTest::newRow("FinishButton") << QWizard::FinishButton << QStringLiteral("qt_wizard_finish"); + QTest::newRow("CancelButton") << QWizard::CancelButton << QStringLiteral("qt_wizard_cancel"); + QTest::newRow("HelpButton") << QWizard::HelpButton << QStringLiteral("__qt__passive_wizardbutton5"); + QTest::newRow("CustomButton1") << QWizard::CustomButton1 << QStringLiteral("__qt__passive_wizardbutton6"); + QTest::newRow("CustomButton2") << QWizard::CustomButton2 << QStringLiteral("__qt__passive_wizardbutton7"); + QTest::newRow("CustomButton3") << QWizard::CustomButton3 << QStringLiteral("__qt__passive_wizardbutton8"); +} + +void tst_QWizard::objectNames() +{ + QFETCH(QWizard::WizardButton, wizardButton); + QFETCH(QString, buttonName); + + QWizard wizard; + QList<QWizard::WizardButton> buttons = QList<QWizard::WizardButton>() + << QWizard::BackButton + << QWizard::NextButton + << QWizard::CommitButton + << QWizard::FinishButton + << QWizard::CancelButton + << QWizard::HelpButton + << QWizard::CustomButton1 + << QWizard::CustomButton2 + << QWizard::CustomButton3 + ; + QVERIFY(buttons.contains(wizardButton)); + QVERIFY(wizard.button(wizardButton)); + QCOMPARE(wizard.button(wizardButton)->objectName(), buttonName); +} + class task177716_CommitPage : public QWizardPage { Q_OBJECT diff --git a/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp index 4f25aab32a..2798d1e22d 100644 --- a/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/widgets/graphicsview/qgraphicsitem/tst_qgraphicsitem.cpp @@ -6458,6 +6458,12 @@ public: void tst_QGraphicsItem::ensureUpdateOnTextItem() { +#ifdef Q_OS_MAC + if (QSysInfo::MacintoshVersion == QSysInfo::MV_10_7) { + QSKIP("This test is unstable on 10.7 in CI"); + } +#endif + QGraphicsScene scene; QGraphicsView view(&scene); view.show(); diff --git a/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp b/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp index b3fba29f81..dfc8465210 100644 --- a/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp +++ b/tests/auto/widgets/graphicsview/qgraphicsscene/tst_qgraphicsscene.cpp @@ -4072,6 +4072,7 @@ void tst_QGraphicsScene::isActive() { + const QRect availableGeometry = QGuiApplication::primaryScreen()->availableGeometry(); QWidget toplevel2; QHBoxLayout *layout = new QHBoxLayout; toplevel2.setLayout(layout); @@ -4085,12 +4086,13 @@ void tst_QGraphicsScene::isActive() QVERIFY(!scene1.hasFocus()); QVERIFY(!scene2.hasFocus()); + toplevel2.move(availableGeometry.topLeft() + QPoint(50, 50)); toplevel2.show(); QApplication::setActiveWindow(&toplevel2); QVERIFY(QTest::qWaitForWindowActive(&toplevel2)); QCOMPARE(QApplication::activeWindow(), &toplevel2); - QVERIFY(scene1.isActive()); + QTRY_VERIFY(scene1.isActive()); QVERIFY(!scene2.isActive()); QVERIFY(scene1.hasFocus()); QVERIFY(!scene2.hasFocus()); @@ -4133,6 +4135,7 @@ void tst_QGraphicsScene::isActive() QVERIFY(!scene2.hasFocus()); QGraphicsView topLevelView; + topLevelView.move(availableGeometry.topLeft() + QPoint(500, 50)); topLevelView.show(); QApplication::setActiveWindow(&topLevelView); topLevelView.setFocus(); diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp index 7a0ba50ff0..37cc6522a2 100644 --- a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp @@ -4687,13 +4687,17 @@ public: void tst_QGraphicsView::hoverLeave() { + const QRect availableGeometry = QGuiApplication::primaryScreen()->availableGeometry(); QGraphicsScene scene; QGraphicsView view(&scene); + view.resize(160, 160); + view.move(availableGeometry.center() - QPoint(80, 80)); GraphicsItemWithHover *item = new GraphicsItemWithHover; scene.addItem(item); // move the cursor out of the way - QCursor::setPos(1,1); + const QPoint outOfWindow = view.geometry().topRight() + QPoint(50, 0); + QCursor::setPos(outOfWindow); view.show(); qApp->setActiveWindow(&view); @@ -4701,16 +4705,14 @@ void tst_QGraphicsView::hoverLeave() QPoint pos = view.viewport()->mapToGlobal(view.mapFromScene(item->mapToScene(10, 10))); QCursor::setPos(pos); - QTest::qWait(200); - QVERIFY(item->receivedEnterEvent); + QTRY_VERIFY(item->receivedEnterEvent); QCOMPARE(item->enterWidget, view.viewport()); - QCursor::setPos(1,1); - QTest::qWait(200); + QCursor::setPos(outOfWindow); #ifdef Q_OS_MAC QEXPECT_FAIL("", "QTBUG-26274 - behaviour regression", Abort); #endif - QVERIFY(item->receivedLeaveEvent); + QTRY_VERIFY(item->receivedLeaveEvent); QCOMPARE(item->leaveWidget, view.viewport()); } diff --git a/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp b/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp index 2dd2089f81..3271b31692 100644 --- a/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp +++ b/tests/auto/widgets/graphicsview/qgraphicswidget/tst_qgraphicswidget.cpp @@ -53,6 +53,7 @@ #include <qwidgetaction.h> #include <qcommonstyle.h> #include <qstylefactory.h> +#include <qscreen.h> #include "../../../qtest-config.h" @@ -1780,8 +1781,11 @@ void tst_QGraphicsWidget::verifyFocusChain() void tst_QGraphicsWidget::updateFocusChainWhenChildDie() { + const QRect availableGeometry = QGuiApplication::primaryScreen()->availableGeometry(); QGraphicsScene scene; QGraphicsView view(&scene); + view.resize(200, 150); + view.move(availableGeometry.topLeft() + QPoint(50, 50)); view.show(); QApplication::setActiveWindow(&view); QVERIFY(QTest::qWaitForWindowActive(&view)); @@ -1801,6 +1805,9 @@ void tst_QGraphicsWidget::updateFocusChainWhenChildDie() QVERIFY(w1_1->hasFocus()); QWidget myWidget(0); QLineEdit edit(&myWidget); + (new QHBoxLayout(&myWidget))->addWidget(&edit); + edit.setMinimumWidth(160); // Windows + myWidget.move(availableGeometry.topLeft() + QPoint(350, 50)); myWidget.show(); edit.setFocus(); QTRY_VERIFY(edit.hasFocus()); @@ -1809,8 +1816,9 @@ void tst_QGraphicsWidget::updateFocusChainWhenChildDie() w->setParentItem(parent); //We don't crash perfect QVERIFY(w); - QTest::mouseMove(view.viewport()); - QTest::mouseClick(view.viewport(), Qt::LeftButton, 0); + const QPoint center(view.viewport()->width() / 2, view.viewport()->height() / 2); + QTest::mouseMove(view.viewport(), center); + QTest::mouseClick(view.viewport(), Qt::LeftButton, 0, center); #ifdef Q_OS_MAC QEXPECT_FAIL("", "QTBUG-23699", Continue); #endif diff --git a/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp b/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp index 0c6d369254..36bf76564f 100644 --- a/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp +++ b/tests/auto/widgets/itemviews/qabstractitemview/tst_qabstractitemview.cpp @@ -58,17 +58,8 @@ #include <qscrollbar.h> #include <qboxlayout.h> #include <qlineedit.h> - -// Will try to wait for the condition while allowing event processing -// for a maximum of 5 seconds. -#define TRY_COMPARE(expr, expected) \ - do { \ - const int step = 50; \ - for (int q = 0; q < 5000 && ((expr) != (expected)); q+=step) { \ - QTest::qWait(step); \ - } \ - QCOMPARE(expr, expected); \ - } while(0) +#include <qscreen.h> +#include <qscopedpointer.h> static inline void setFrameless(QWidget *w) { @@ -78,6 +69,22 @@ static inline void setFrameless(QWidget *w) w->setWindowFlags(flags); } +static inline void centerOnScreen(QWidget *w) +{ + const QPoint offset = QPoint(w->width() / 2, w->height() / 2); + w->move(QGuiApplication::primaryScreen()->availableGeometry().center() - offset); +} + +// Move cursor out of widget area to avoid undesired interaction on Mac. +static inline void moveCursorAway(const QWidget *topLevel) +{ +#ifndef QT_NO_CURSOR + QCursor::setPos(topLevel->geometry().topRight() + QPoint(100, 0)); +#else + Q_UNUSED(topLevel) +#endif +} + class TestView : public QAbstractItemView { Q_OBJECT @@ -374,25 +381,27 @@ void tst_QAbstractItemView::emptyModels() { QFETCH(QString, viewType); - TestView *view = 0; + QScopedPointer<QAbstractItemView> view; if (viewType == "QListView") - view = reinterpret_cast<TestView*>(new QListView()); + view.reset(new QListView()); else if (viewType == "QTableView") - view = reinterpret_cast<TestView*>(new QTableView()); + view.reset(new QTableView()); else if (viewType == "QTreeView") - view = reinterpret_cast<TestView*>(new QTreeView()); + view.reset(new QTreeView()); else if (viewType == "QHeaderView") - view = reinterpret_cast<TestView*>(new QHeaderView(Qt::Vertical)); + view.reset(new QHeaderView(Qt::Vertical)); else QVERIFY(0); + centerOnScreen(view.data()); + moveCursorAway(view.data()); view->show(); + QVERIFY(QTest::qWaitForWindowExposed(view.data())); QVERIFY(!view->model()); QVERIFY(!view->selectionModel()); //QVERIFY(view->itemDelegate() != 0); - basic_tests(view); - delete view; + basic_tests(reinterpret_cast<TestView*>(view.data())); } void tst_QAbstractItemView::setModel_data() @@ -408,24 +417,28 @@ void tst_QAbstractItemView::setModel_data() void tst_QAbstractItemView::setModel() { QFETCH(QString, viewType); - TestView *view = 0; + + QScopedPointer<QAbstractItemView> view; + if (viewType == "QListView") - view = reinterpret_cast<TestView*>(new QListView()); + view.reset(new QListView()); else if (viewType == "QTableView") - view = reinterpret_cast<TestView*>(new QTableView()); + view.reset(new QTableView()); else if (viewType == "QTreeView") - view = reinterpret_cast<TestView*>(new QTreeView()); + view.reset(new QTreeView()); else if (viewType == "QHeaderView") - view = reinterpret_cast<TestView*>(new QHeaderView(Qt::Vertical)); + view.reset(new QHeaderView(Qt::Vertical)); else QVERIFY(0); + centerOnScreen(view.data()); + moveCursorAway(view.data()); view->show(); + QVERIFY(QTest::qWaitForWindowExposed(view.data())); QStandardItemModel model(20,20); view->setModel(0); view->setModel(&model); - basic_tests(view); - delete view; + basic_tests(reinterpret_cast<TestView*>(view.data())); } void tst_QAbstractItemView::basic_tests(TestView *view) @@ -636,7 +649,10 @@ void tst_QAbstractItemView::noModel() view.setModel(&model); // Make the viewport smaller than the contents, so that we can scroll view.resize(100,100); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); + QVERIFY(QTest::qWaitForWindowExposed(&view)); // make sure that the scrollbars are not at value 0 view.scrollTo(view.model()->index(10,10)); @@ -656,7 +672,10 @@ void tst_QAbstractItemView::dragSelect() QTableView view; view.setModel(&model); + centerOnScreen(&view); + moveCursorAway(&view); view.setVisible(true); + QVERIFY(QTest::qWaitForWindowExposed(&view)); const int delay = 2; for (int i = 0; i < 2; ++i) { @@ -677,7 +696,10 @@ void tst_QAbstractItemView::rowDelegate() QTableView view; view.setModel(&model); view.setItemDelegateForRow(3, &delegate); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); + QVERIFY(QTest::qWaitForWindowExposed(&view)); QModelIndex index = model.index(3, 0); view.openPersistentEditor(index); @@ -694,7 +716,10 @@ void tst_QAbstractItemView::columnDelegate() QTableView view; view.setModel(&model); view.setItemDelegateForColumn(3, &delegate); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); + QVERIFY(QTest::qWaitForWindowExposed(&view)); QModelIndex index = model.index(0, 3); view.openPersistentEditor(index); @@ -747,11 +772,13 @@ void tst_QAbstractItemView::persistentEditorFocus() view.setCurrentIndex(model.index(0, 0)); QCOMPARE(view.currentIndex(), model.index(0, 0)); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); - QTRY_VERIFY(view.isVisible()); + QVERIFY(QTest::qWaitForWindowExposed(&view)); for (int i = 0; i < list.count(); ++i) { - TRY_COMPARE(list.at(i)->isVisible(), true); + QTRY_VERIFY(list.at(i)->isVisible()); QPoint p = QPoint(5, 5); QMouseEvent mouseEvent(QEvent::MouseButtonPress, p, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); @@ -1045,6 +1072,8 @@ void tst_QAbstractItemView::setItemDelegate() } } } + centerOnScreen(&v); + moveCursorAway(&v); v.show(); #ifdef Q_WS_X11 QCursor::setPos(v.geometry().center()); @@ -1056,7 +1085,7 @@ void tst_QAbstractItemView::setItemDelegate() v.edit(index); // This will close the editor - TRY_COMPARE(QApplication::focusWidget() == 0, false); + QTRY_VERIFY(QApplication::focusWidget()); QWidget *editor = QApplication::focusWidget(); QVERIFY(editor); editor->hide(); @@ -1122,20 +1151,25 @@ void tst_QAbstractItemView::setCurrentIndex() QFETCH(int, itemFlags); QFETCH(bool, result); - TestView *view = 0; + QScopedPointer<QAbstractItemView> view; + if (viewType == "QListView") - view = reinterpret_cast<TestView*>(new QListView()); + view.reset(new QListView()); else if (viewType == "QTableView") - view = reinterpret_cast<TestView*>(new QTableView()); + view.reset(new QTableView()); else if (viewType == "QTreeView") - view = reinterpret_cast<TestView*>(new QTreeView()); + view.reset(new QTreeView()); else if (viewType == "QHeaderView") - view = reinterpret_cast<TestView*>(new QHeaderView(Qt::Vertical)); + view.reset(new QHeaderView(Qt::Vertical)); else QVERIFY(0); + + centerOnScreen(view.data()); + moveCursorAway(view.data()); view->show(); + QVERIFY(QTest::qWaitForWindowExposed(view.data())); - QStandardItemModel *model = new QStandardItemModel(view); + QStandardItemModel *model = new QStandardItemModel(view.data()); QStandardItem *item = new QStandardItem("first item"); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); model->appendRow(item); @@ -1150,8 +1184,6 @@ void tst_QAbstractItemView::setCurrentIndex() QVERIFY(view->currentIndex() == model->index(0,0)); view->setCurrentIndex(model->index(1,0)); QVERIFY(view->currentIndex() == model->index(result ? 1 : 0,0)); - - delete view; } void tst_QAbstractItemView::task221955_selectedEditor() @@ -1170,11 +1202,13 @@ void tst_QAbstractItemView::task221955_selectedEditor() tree.setItemWidget(dummy, 0, button = new QPushButton("More...")); button->setAutoFillBackground(true); // as recommended in doc + centerOnScreen(&tree); + moveCursorAway(&tree); tree.show(); tree.setFocus(); tree.setCurrentIndex(tree.model()->index(1,0)); - QTest::qWait(100); QApplication::setActiveWindow(&tree); + QVERIFY(QTest::qWaitForWindowActive(&tree)); QVERIFY(! tree.selectionModel()->selectedIndexes().contains(tree.model()->index(3,0))); @@ -1218,9 +1252,11 @@ void tst_QAbstractItemView::task250754_fontChange() } tree.setModel(m); + w.resize(160, 240); // Minimum width for windows with frame on Windows 8 + centerOnScreen(&w); + moveCursorAway(&w); w.show(); - w.resize(150,240); - QTest::qWait(30); + QVERIFY(QTest::qWaitForWindowExposed(&w)); QFont font = tree.font(); font.setPixelSize(10); tree.setFont(font); @@ -1244,8 +1280,10 @@ void tst_QAbstractItemView::task200665_itemEntered() QStandardItemModel model(1000,1); QListView view; view.setModel(&model); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); - QTest::qWait(200); + QVERIFY(QTest::qWaitForWindowExposed(&view)); QRect rect = view.visualRect(model.index(0,0)); QCursor::setPos( view.viewport()->mapToGlobal(rect.center()) ); QSignalSpy spy(&view, SIGNAL(entered(QModelIndex))); @@ -1267,7 +1305,10 @@ void tst_QAbstractItemView::task257481_emptyEditor() QTreeView treeView; treeView.setRootIsDecorated(false); treeView.setModel(&model); + centerOnScreen(&treeView); + moveCursorAway(&treeView); treeView.show(); + QVERIFY(QTest::qWaitForWindowExposed(&treeView)); treeView.edit(model.index(0,0)); QList<QLineEdit *> lineEditors = treeView.viewport()->findChildren<QLineEdit *>(); @@ -1298,14 +1339,16 @@ void tst_QAbstractItemView::shiftArrowSelectionAfterScrolling() } QListView view; - view.setFixedSize(150, 250); + view.setFixedSize(160, 250); // Minimum width for windows with frame on Windows 8 view.setFlow(QListView::LeftToRight); view.setGridSize(QSize(100, 100)); view.setSelectionMode(QListView::ExtendedSelection); view.setViewMode(QListView::IconMode); view.setModel(&model); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); - QTest::qWait(30); + QVERIFY(QTest::qWaitForWindowExposed(&view)); QModelIndex index0 = model.index(0, 0); QModelIndex index1 = model.index(1, 0); @@ -1333,14 +1376,16 @@ void tst_QAbstractItemView::shiftSelectionAfterRubberbandSelection() } QListView view; - view.setFixedSize(150, 450); + view.setFixedSize(160, 450); // Minimum width for windows with frame on Windows 8 view.setFlow(QListView::LeftToRight); view.setGridSize(QSize(100, 100)); view.setSelectionMode(QListView::ExtendedSelection); view.setViewMode(QListView::IconMode); view.setModel(&model); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); - QTest::qWait(30); + QVERIFY(QTest::qWaitForWindowExposed(&view)); QModelIndex index0 = model.index(0, 0); QModelIndex index1 = model.index(1, 0); @@ -1408,14 +1453,16 @@ void tst_QAbstractItemView::ctrlRubberbandSelection() } QListView view; - view.setFixedSize(150, 450); + view.setFixedSize(160, 450); // Minimum width for windows with frame on Windows 8 view.setFlow(QListView::LeftToRight); view.setGridSize(QSize(100, 100)); view.setSelectionMode(QListView::ExtendedSelection); view.setViewMode(QListView::IconMode); view.setModel(&model); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); - QTest::qWait(30); + QVERIFY(QTest::qWaitForWindowExposed(&view)); QModelIndex index1 = model.index(1, 0); QModelIndex index2 = model.index(2, 0); @@ -1454,6 +1501,8 @@ void tst_QAbstractItemView::QTBUG6407_extendedSelection() font.setPixelSize(10); view.setFont(font); view.resize(200,240); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); QApplication::setActiveWindow(&view); @@ -1493,7 +1542,11 @@ void tst_QAbstractItemView::QTBUG6753_selectOnSelection() for (int j = 0; j < table.columnCount(); ++j) table.setItem(i, j, new QTableWidgetItem("choo-be-doo-wah")); + centerOnScreen(&table); + moveCursorAway(&table); table.show(); + QVERIFY(QTest::qWaitForWindowExposed(&table)); + table.setSelectionMode(QAbstractItemView::ExtendedSelection); table.selectAll(); QVERIFY(QTest::qWaitForWindowExposed(&table)); @@ -1523,6 +1576,8 @@ void tst_QAbstractItemView::testClickedSignal() { QTableWidget view(5, 5); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); QApplication::setActiveWindow(&view); QVERIFY(QTest::qWaitForWindowActive(&view)); @@ -1591,6 +1646,8 @@ void tst_QAbstractItemView::testChangeEditorState() view.setEditTriggers(QAbstractItemView::CurrentChanged); view.setItemDelegate(new StateChangeDelegate); view.setModel(&model); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); QApplication::setActiveWindow(&view); QVERIFY(QTest::qWaitForWindowActive(&view)); @@ -1607,7 +1664,10 @@ void tst_QAbstractItemView::deselectInSingleSelection() s.setRowCount(10); s.setColumnCount(10); view.setModel(&s); + centerOnScreen(&view); + moveCursorAway(&view); view.show(); + QVERIFY(QTest::qWaitForWindowExposed(&view)); view.setSelectionMode(QAbstractItemView::SingleSelection); view.setEditTriggers(QAbstractItemView::NoEditTriggers); QApplication::setActiveWindow(&view); @@ -1650,6 +1710,8 @@ void tst_QAbstractItemView::testNoActivateOnDisabledItem() model.setItem(0, 0, item); item->setFlags(Qt::NoItemFlags); treeView.setModel(&model); + centerOnScreen(&treeView); + moveCursorAway(&treeView); treeView.show(); QApplication::setActiveWindow(&treeView); diff --git a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp index 398b1b4d98..3e6df0f136 100644 --- a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp +++ b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp @@ -368,6 +368,8 @@ void tst_QHeaderView::getSetCheck() QCOMPARE(0, obj1.minimumSectionSize()); obj1.setMinimumSectionSize(99999); QCOMPARE(99999, obj1.minimumSectionSize()); + obj1.setMinimumSectionSize(-1); + QVERIFY(obj1.minimumSectionSize() < 100); // int QHeaderView::offset() // void QHeaderView::setOffset(int) diff --git a/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp b/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp index 8d31fcdf13..ccdce1fe0c 100644 --- a/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp +++ b/tests/auto/widgets/itemviews/qtreeview/tst_qtreeview.cpp @@ -259,6 +259,7 @@ private slots: void taskQTBUG_25333_adjustViewOptionsForIndex(); void taskQTBUG_18539_emitLayoutChanged(); void taskQTBUG_8176_emitOnExpandAll(); + void taskQTBUG_34717_collapseAtBottom(); void testInitialFocus(); }; @@ -4240,6 +4241,35 @@ void tst_QTreeView::taskQTBUG_8176_emitOnExpandAll() QCOMPARE(spy2.size(), 1); // item2 is collapsed } +// From QTBUG_34717 (QTreeWidget crashes when scrolling to the end +// of an expanded tree, then collapse all) +// The test passes simply if it doesn't crash. +void tst_QTreeView::taskQTBUG_34717_collapseAtBottom() +{ + QTreeWidget treeWidget; + treeWidget.header()->setSectionResizeMode(QHeaderView::ResizeToContents); + treeWidget.setColumnCount(2); + QTreeWidgetItem *mainItem = new QTreeWidgetItem(&treeWidget, QStringList() << "Root"); + for (int i = 0; i < 200; ++i) { + QTreeWidgetItem *item = new QTreeWidgetItem(mainItem, QStringList(QString("Item"))); + new QTreeWidgetItem(item, QStringList() << "Child" << "1"); + new QTreeWidgetItem(item, QStringList() << "Child" << "2"); + new QTreeWidgetItem(item, QStringList() << "Child" << "3"); + } + treeWidget.show(); + treeWidget.expandAll(); + treeWidget.scrollToBottom(); + treeWidget.collapseAll(); + + treeWidget.setAnimated(true); + treeWidget.expandAll(); + treeWidget.scrollToBottom(); + mainItem->setExpanded(false); + + PublicView *pview = (PublicView*) &treeWidget; + QVERIFY(pview->sizeHintForColumn(1) >= 0); +} + void tst_QTreeView::testInitialFocus() { QTreeWidget treeWidget; diff --git a/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp b/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp index 16bd4a6f7b..e13dfe836f 100644 --- a/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp +++ b/tests/auto/widgets/kernel/qapplication/tst_qapplication.cpp @@ -153,6 +153,7 @@ private slots: void focusChanged(); void focusOut(); + void focusMouseClick(); void execAfterExit(); @@ -1773,6 +1774,63 @@ void tst_QApplication::focusOut() QTest::qWait(2000); } +class SpontaneousEvent +{ + Q_GADGET + QDOC_PROPERTY(bool accepted READ isAccepted WRITE setAccepted) + Q_ENUMS(Type) +public: + enum Type { + Void + }; + + virtual ~SpontaneousEvent() {} + + QEventPrivate *d; + ushort t; + + ushort posted : 1; + ushort spont : 1; +}; + +void tst_QApplication::focusMouseClick() +{ + int argc = 1; + QApplication app(argc, &argv0); + + QWidget w; + w.setFocusPolicy(Qt::StrongFocus); + QWidget w2(&w); + w2.setFocusPolicy(Qt::TabFocus); + w.show(); + w.setFocus(); + QTRY_COMPARE(QApplication::focusWidget(), &w); + + // front most widget has Qt::TabFocus, parent widget accepts clicks as well + // now send a mouse button press event and check what happens with the focus + // it should be given to the parent widget + QMouseEvent ev(QEvent::MouseButtonPress, QPointF(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); + reinterpret_cast<SpontaneousEvent *>(&ev)->spont = 1; + QVERIFY(ev.spontaneous()); + qApp->notify(&w2, &ev); + QCOMPARE(QApplication::focusWidget(), &w); + + // then we give the inner widget strong focus -> it should get focus + w2.setFocusPolicy(Qt::StrongFocus); + reinterpret_cast<SpontaneousEvent *>(&ev)->spont = 1; + QVERIFY(ev.spontaneous()); + qApp->notify(&w2, &ev); + QTRY_COMPARE(QApplication::focusWidget(), &w2); + + // now back to tab focus and click again (it already had focus) -> focus should stay + // (focus was revoked as of QTBUG-34042) + w2.setFocusPolicy(Qt::TabFocus); + reinterpret_cast<SpontaneousEvent *>(&ev)->spont = 1; + QVERIFY(ev.spontaneous()); + qApp->notify(&w2, &ev); + QCOMPARE(QApplication::focusWidget(), &w2); +} + void tst_QApplication::execAfterExit() { int argc = 1; diff --git a/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp b/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp index 135605f185..d04b812878 100644 --- a/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp +++ b/tests/auto/widgets/kernel/qformlayout/tst_qformlayout.cpp @@ -47,6 +47,7 @@ #include <qproxystyle.h> #include <qsizepolicy.h> +#include <QtWidgets/QCheckBox> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> @@ -347,6 +348,19 @@ void tst_QFormLayout::spacing() style->hspacing = 20; //QCOMPARE(fl->spacing(), 20); + + + // Do not assert if spacings are negative (QTBUG-34731) + style->vspacing = -1; + style->hspacing = -1; + QLabel *label = new QLabel(tr("Asserts")); + QCheckBox *checkBox = new QCheckBox(tr("Yes")); + fl->setWidget(0, QFormLayout::LabelRole, label); + fl->setWidget(1, QFormLayout::FieldRole, checkBox); + w->resize(200, 100); + w->show(); + QVERIFY(QTest::qWaitForWindowExposed(w)); + delete w; delete style; } diff --git a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp index 2da8df6116..de028aa462 100644 --- a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp +++ b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp @@ -75,6 +75,7 @@ #include <qproxystyle.h> #include <QtWidgets/QGraphicsView> #include <QtWidgets/QGraphicsProxyWidget> +#include <QtGui/qwindow.h> #include "../../../qtest-config.h" @@ -172,6 +173,24 @@ static inline void centerOnScreen(QWidget *w) w->move(QGuiApplication::primaryScreen()->availableGeometry().center() - offset); } +#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT) +static inline void setWindowsAnimationsEnabled(bool enabled) +{ + ANIMATIONINFO animation = { sizeof(ANIMATIONINFO), enabled }; + SystemParametersInfo(SPI_SETANIMATION, 0, &animation, 0); +} + +static inline bool windowsAnimationsEnabled() +{ + ANIMATIONINFO animation = { sizeof(ANIMATIONINFO), 0 }; + SystemParametersInfo(SPI_GETANIMATION, 0, &animation, 0); + return animation.iMinAnimate; +} +#else // Q_OS_WIN && !Q_OS_WINCE && !Q_OS_WINRT +inline void setWindowsAnimationsEnabled(bool) {} +static inline bool windowsAnimationsEnabled() { return false; } +#endif // !Q_OS_WIN || Q_OS_WINCE || Q_OS_WINRT + class tst_QWidget : public QObject { Q_OBJECT @@ -427,6 +446,7 @@ private: QWidget *testWidget; const QString m_platform; + const bool m_windowsAnimationsEnabled; }; bool tst_QWidget::ensureScreenSize(int width, int height) @@ -581,8 +601,12 @@ void tst_QWidget::getSetCheck() #endif } -tst_QWidget::tst_QWidget() : m_platform(qApp->platformName().toLower()) +tst_QWidget::tst_QWidget() + : m_platform(qApp->platformName().toLower()) + , m_windowsAnimationsEnabled(windowsAnimationsEnabled()) { + if (m_windowsAnimationsEnabled) // Disable animations which can interfere with screen grabbing in moveChild(), showAndMoveChild() + setWindowsAnimationsEnabled(false); QFont font; font.setBold(true); font.setPointSize(42); @@ -598,6 +622,8 @@ tst_QWidget::tst_QWidget() : m_platform(qApp->platformName().toLower()) tst_QWidget::~tst_QWidget() { + if (m_windowsAnimationsEnabled) + setWindowsAnimationsEnabled(m_windowsAnimationsEnabled); } class BezierViewer : public QWidget { @@ -4753,8 +4779,8 @@ void tst_QWidget::windowMoveResize() class ColorWidget : public QWidget { public: - ColorWidget(QWidget *parent = 0, const QColor &c = QColor(Qt::red)) - : QWidget(parent, Qt::FramelessWindowHint), color(c), enters(0), leaves(0) + ColorWidget(QWidget *parent = 0, Qt::WindowFlags f = 0, const QColor &c = QColor(Qt::red)) + : QWidget(parent, f), color(c), enters(0), leaves(0) { QPalette opaquePalette = palette(); opaquePalette.setColor(backgroundRole(), color); @@ -4785,31 +4811,79 @@ public: int leaves; }; -#define VERIFY_COLOR(region, color) { \ +static inline QByteArray msgRgbMismatch(unsigned actual, unsigned expected) +{ + return QByteArrayLiteral("Color mismatch, 0x") + QByteArray::number(actual, 16) + + QByteArrayLiteral(" != 0x") + QByteArray::number(expected, 16); +} + +#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT) +QT_BEGIN_NAMESPACE +extern Q_GUI_EXPORT QPixmap qt_pixmapFromWinHBITMAP(HBITMAP bitmap, int hbitmapFormat = 0); +QT_END_NAMESPACE + +// grabs the window *without including any overlapping windows* +static QPixmap grabWindow(QWindow *window, int x, int y, int width, int height) +{ + const HWND hwnd = (HWND)window->winId(); + + // Create and setup bitmap + const HDC displayDc = ::GetDC(0); + const HDC bitmapDc = ::CreateCompatibleDC(displayDc); + const HBITMAP bitmap = ::CreateCompatibleBitmap(displayDc, width, height); + const HGDIOBJ oldBitmap = ::SelectObject(bitmapDc, bitmap); + + // copy data + const HDC windowDc = ::GetDC(hwnd); + ::BitBlt(bitmapDc, 0, 0, width, height, windowDc, x, y, SRCCOPY); + + // clean up all but bitmap + ::ReleaseDC(hwnd, windowDc); + ::SelectObject(bitmapDc, oldBitmap); + ::DeleteDC(bitmapDc); + + const QPixmap pixmap = qt_pixmapFromWinHBITMAP(bitmap); + + ::DeleteObject(bitmap); + ::ReleaseDC(0, displayDc); + + return pixmap; +} +#else +// fallback for other platforms. +static QPixmap grabWindow(QWindow *window, int x, int y, int width, int height) +{ + QScreen *screen = window->screen(); + return screen ? screen->grabWindow(window->winId(), x, y, width, height) : QPixmap(); +} +#endif //defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT) + +#define VERIFY_COLOR(child, region, color) do { \ const QRegion r = QRegion(region); \ - QScreen *screen = qApp->primaryScreen(); \ - const WId desktopWinId = QDesktopWidget().winId(); \ + QWindow *window = child.window()->windowHandle(); \ + Q_ASSERT(window); \ + const QPoint offset = child.mapTo(child.window(), QPoint(0,0)); \ for (int i = 0; i < r.rects().size(); ++i) { \ - const QRect rect = r.rects().at(i); \ + const QRect rect = r.rects().at(i).translated(offset); \ for (int t = 0; t < 5; t++) { \ - const QPixmap pixmap = screen->grabWindow(desktopWinId, \ - rect.left(), rect.top(), \ - rect.width(), rect.height()); \ + const QPixmap pixmap = grabWindow(window, \ + rect.left(), rect.top(), \ + rect.width(), rect.height()); \ QCOMPARE(pixmap.size(), rect.size()); \ QPixmap expectedPixmap(pixmap); /* ensure equal formats */ \ - expectedPixmap.detach(); \ + expectedPixmap.detach(); \ expectedPixmap.fill(color); \ - QImage image = pixmap.toImage(); \ + QImage image = pixmap.toImage(); \ uint alphaCorrection = image.format() == QImage::Format_RGB32 ? 0xff000000 : 0; \ - uint firstPixel = image.pixel(0,0) | alphaCorrection; \ - if ( firstPixel != QColor(color).rgb() && t < 4 ) \ + uint firstPixel = image.pixel(0,0) | alphaCorrection; \ + if ( firstPixel != QColor(color).rgb() && t < 4 ) \ { QTest::qWait(200); continue; } \ - QCOMPARE(firstPixel, QColor(color).rgb()); \ + QVERIFY2(firstPixel == QColor(color).rgb(), msgRgbMismatch(firstPixel, QColor(color).rgb())); \ QCOMPARE(pixmap, expectedPixmap); \ break; \ } \ } \ -} +} while (0) void tst_QWidget::popupEnterLeave() { @@ -4817,7 +4891,7 @@ void tst_QWidget::popupEnterLeave() parent.setWindowFlags(Qt::FramelessWindowHint); parent.setGeometry(10, 10, 200, 100); - ColorWidget alien(&parent, Qt::black); + ColorWidget alien(&parent, Qt::Widget, Qt::black); alien.setGeometry(0, 0, 10, 10); alien.show(); @@ -4868,34 +4942,32 @@ void tst_QWidget::moveChild_data() void tst_QWidget::moveChild() { -#if defined(UBUNTU_ONEIRIC) - QSKIP("QTBUG-30566 - Unstable auto-test"); -#endif QFETCH(QPoint, offset); - ColorWidget parent; + ColorWidget parent(0, Qt::Window | Qt::WindowStaysOnTopHint); // prevent custom styles parent.setStyle(QStyleFactory::create(QLatin1String("Windows"))); - ColorWidget child(&parent, Qt::blue); + ColorWidget child(&parent, Qt::Widget, Qt::blue); #ifndef Q_OS_WINCE - parent.setGeometry(QRect(QPoint(QApplication::desktop()->availableGeometry(&parent).topLeft()), - QSize(100, 100))); + parent.setGeometry(QRect(QPoint(QApplication::desktop()->availableGeometry(&parent).topLeft()) + QPoint(50, 50), + QSize(200, 200))); #else parent.setGeometry(60, 60, 150, 150); #endif child.setGeometry(25, 25, 50, 50); +#ifndef QT_NO_CURSOR // Try to make sure the cursor is not in a taskbar area to prevent tooltips or window highlighting + QCursor::setPos(parent.geometry().topRight() + QPoint(50 , 50)); +#endif parent.show(); QVERIFY(QTest::qWaitForWindowExposed(&parent)); QTest::qWait(30); - const QPoint tlwOffset = parent.geometry().topLeft(); QTRY_COMPARE(parent.r, QRegion(parent.rect()) - child.geometry()); QTRY_COMPARE(child.r, QRegion(child.rect())); - VERIFY_COLOR(child.geometry().translated(tlwOffset), + VERIFY_COLOR(child, child.rect(), child.color); - VERIFY_COLOR(QRegion(parent.geometry()) - child.geometry().translated(tlwOffset), - parent.color); + VERIFY_COLOR(parent, QRegion(parent.rect()) - child.geometry(), parent.color); parent.reset(); child.reset(); @@ -4913,10 +4985,8 @@ void tst_QWidget::moveChild() // should be scrolled in backingstore QCOMPARE(child.r, QRegion()); #endif - VERIFY_COLOR(child.geometry().translated(tlwOffset), - child.color); - VERIFY_COLOR(QRegion(parent.geometry()) - child.geometry().translated(tlwOffset), - parent.color); + VERIFY_COLOR(child, child.rect(), child.color); + VERIFY_COLOR(parent, QRegion(parent.rect()) - child.geometry(), parent.color); } void tst_QWidget::showAndMoveChild() @@ -4924,7 +4994,7 @@ void tst_QWidget::showAndMoveChild() #if defined(UBUNTU_ONEIRIC) QSKIP("QTBUG-30566 - Unstable auto-test"); #endif - QWidget parent(0, Qt::FramelessWindowHint); + QWidget parent(0, Qt::Window | Qt::WindowStaysOnTopHint); // prevent custom styles parent.setStyle(QStyleFactory::create(QLatin1String("Windows"))); @@ -4932,6 +5002,9 @@ void tst_QWidget::showAndMoveChild() QRect desktopDimensions = desktop.availableGeometry(&parent); desktopDimensions = desktopDimensions.adjusted(64, 64, -64, -64); +#ifndef QT_NO_CURSOR // Try to make sure the cursor is not in a taskbar area to prevent tooltips or window highlighting + QCursor::setPos(desktopDimensions.topRight() + QPoint(40, 40)); +#endif parent.setGeometry(desktopDimensions); parent.setPalette(Qt::red); parent.show(); @@ -4939,7 +5012,6 @@ void tst_QWidget::showAndMoveChild() QVERIFY(QTest::qWaitForWindowActive(&parent)); QTest::qWait(10); - const QPoint tlwOffset = parent.geometry().topLeft(); QWidget child(&parent); child.resize(desktopDimensions.width()/2, desktopDimensions.height()/2); child.setPalette(Qt::blue); @@ -4951,8 +5023,8 @@ void tst_QWidget::showAndMoveChild() child.move(desktopDimensions.width()/2, desktopDimensions.height()/2); qApp->processEvents(); - VERIFY_COLOR(child.geometry().translated(tlwOffset), Qt::blue); - VERIFY_COLOR(QRegion(parent.geometry()) - child.geometry().translated(tlwOffset), Qt::red); + VERIFY_COLOR(child, child.rect(), Qt::blue); + VERIFY_COLOR(parent, QRegion(parent.rect()) - child.geometry(), Qt::red); } // Cocoa only has rect granularity. @@ -4962,13 +5034,13 @@ void tst_QWidget::subtractOpaqueSiblings() QWidget w; w.setGeometry(50, 50, 300, 300); - ColorWidget *large = new ColorWidget(&w, Qt::red); + ColorWidget *large = new ColorWidget(&w, Qt::Widget, Qt::red); large->setGeometry(50, 50, 200, 200); - ColorWidget *medium = new ColorWidget(large, Qt::gray); + ColorWidget *medium = new ColorWidget(large, Qt::Widget, Qt::gray); medium->setGeometry(50, 50, 100, 100); - ColorWidget *tall = new ColorWidget(&w, Qt::blue); + ColorWidget *tall = new ColorWidget(&w, Qt::Widget, Qt::blue); tall->setGeometry(100, 30, 50, 100); w.show(); @@ -7051,7 +7123,7 @@ void tst_QWidget::repaintWhenChildDeleted() QTest::qWait(1000); } #endif - ColorWidget w(0, Qt::red); + ColorWidget w(0, Qt::FramelessWindowHint, Qt::red); #if !defined(Q_OS_WINCE) QPoint startPoint = QApplication::desktop()->availableGeometry(&w).topLeft(); startPoint.rx() += 50; @@ -7067,7 +7139,7 @@ void tst_QWidget::repaintWhenChildDeleted() w.r = QRegion(); { - ColorWidget child(&w, Qt::blue); + ColorWidget child(&w, Qt::Widget, Qt::blue); child.setGeometry(10, 10, 10, 10); child.show(); QTest::qWait(10); @@ -7082,7 +7154,7 @@ void tst_QWidget::repaintWhenChildDeleted() // task 175114 void tst_QWidget::hideOpaqueChildWhileHidden() { - ColorWidget w(0, Qt::red); + ColorWidget w(0, Qt::FramelessWindowHint, Qt::red); #if !defined(Q_OS_WINCE) QPoint startPoint = QApplication::desktop()->availableGeometry(&w).topLeft(); startPoint.rx() += 50; @@ -7092,10 +7164,10 @@ void tst_QWidget::hideOpaqueChildWhileHidden() w.setGeometry(60, 60, 110, 110); #endif - ColorWidget child(&w, Qt::blue); + ColorWidget child(&w, Qt::Widget, Qt::blue); child.setGeometry(10, 10, 80, 80); - ColorWidget child2(&child, Qt::white); + ColorWidget child2(&child, Qt::Widget, Qt::white); child2.setGeometry(10, 10, 60, 60); w.show(); @@ -9782,18 +9854,16 @@ void tst_QWidget::underMouse() // Move the mouse cursor to a safe location QCursor::setPos(0,0); - ColorWidget topLevelWidget(0, Qt::blue); - ColorWidget childWidget1(&topLevelWidget, Qt::yellow); - ColorWidget childWidget2(&topLevelWidget, Qt::black); - ColorWidget popupWidget(0, Qt::green); + ColorWidget topLevelWidget(0, Qt::FramelessWindowHint, Qt::blue); + ColorWidget childWidget1(&topLevelWidget, Qt::Widget, Qt::yellow); + ColorWidget childWidget2(&topLevelWidget, Qt::Widget, Qt::black); + ColorWidget popupWidget(0, Qt::Popup, Qt::green); topLevelWidget.setObjectName("topLevelWidget"); childWidget1.setObjectName("childWidget1"); childWidget2.setObjectName("childWidget2"); popupWidget.setObjectName("popupWidget"); - popupWidget.setWindowFlags(Qt::Popup); - topLevelWidget.setGeometry(100, 100, 300, 300); childWidget1.setGeometry(20, 20, 100, 100); childWidget2.setGeometry(20, 120, 100, 100); diff --git a/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp b/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp index c17a03e058..cd6433bbe7 100644 --- a/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp +++ b/tests/auto/widgets/kernel/qwindowcontainer/tst_qwindowcontainer.cpp @@ -46,6 +46,8 @@ #include <qwindow.h> #include <qwidget.h> +#include <qdockwidget.h> +#include <qmainwindow.h> class Window : public QWindow @@ -80,6 +82,7 @@ private slots: void testUnparenting(); void testActivation(); void testAncestorChange(); + void testDockWidget(); }; @@ -278,6 +281,7 @@ void tst_QWindowContainer::testAncestorChange() newRoot->setGeometry(100, 100, 200, 200); newRoot->show(); QVERIFY(QTest::qWaitForWindowExposed(newRoot)); + QCOMPARE(newRoot->windowHandle(), window->parent()); // newRoot // + right // + container @@ -285,6 +289,31 @@ void tst_QWindowContainer::testAncestorChange() QCOMPARE(window->geometry(), QRect(100, 0, 100, 100)); } + +void tst_QWindowContainer::testDockWidget() +{ + QMainWindow mainWindow; + mainWindow.resize(200, 200); + + QDockWidget *dock = new QDockWidget(); + QWindow *window = new QWindow(); + QWidget *container = QWidget::createWindowContainer(window); + dock->setWidget(container); + mainWindow.addDockWidget(Qt::RightDockWidgetArea, dock); + + mainWindow.show(); + QVERIFY(QTest::qWaitForWindowExposed(&mainWindow)); + QVERIFY(window->parent() == mainWindow.window()->windowHandle()); + + QTest::qWait(1000); + dock->setFloating(true); + QTRY_VERIFY(window->parent() != mainWindow.window()->windowHandle()); + + QTest::qWait(1000); + dock->setFloating(false); + QTRY_VERIFY(window->parent() == mainWindow.window()->windowHandle()); +} + QTEST_MAIN(tst_QWindowContainer) #include "tst_qwindowcontainer.moc" diff --git a/tests/auto/widgets/widgets/qkeysequenceedit/tst_qkeysequenceedit.cpp b/tests/auto/widgets/widgets/qkeysequenceedit/tst_qkeysequenceedit.cpp index 8c010abfe6..1434d98e59 100644 --- a/tests/auto/widgets/widgets/qkeysequenceedit/tst_qkeysequenceedit.cpp +++ b/tests/auto/widgets/widgets/qkeysequenceedit/tst_qkeysequenceedit.cpp @@ -43,6 +43,8 @@ #include <QtTest/QtTest> #include <QKeySequenceEdit> +#include <QLineEdit> +#include <QString> Q_DECLARE_METATYPE(Qt::Key) Q_DECLARE_METATYPE(Qt::KeyboardModifiers) @@ -55,6 +57,7 @@ private slots: void testSetters(); void testKeys_data(); void testKeys(); + void testLineEditContents(); }; void tst_QKeySequenceEdit::testSetters() @@ -100,5 +103,26 @@ void tst_QKeySequenceEdit::testKeys() QTRY_COMPARE(spy.count(), 1); } +void tst_QKeySequenceEdit::testLineEditContents() +{ + QKeySequenceEdit edit; + QLineEdit *le = edit.findChild<QLineEdit*>(); + QVERIFY(le); + + QCOMPARE(le->text(), QString()); + + edit.setKeySequence(QKeySequence::New); + QCOMPARE(edit.keySequence(), QKeySequence(QKeySequence::New)); + + edit.clear(); + QCOMPARE(le->text(), QString()); + + edit.setKeySequence(QKeySequence::New); + QVERIFY(le->text() != QString()); + + edit.setKeySequence(QKeySequence()); + QCOMPARE(le->text(), QString()); +} + QTEST_MAIN(tst_QKeySequenceEdit) #include "tst_qkeysequenceedit.moc" diff --git a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp index 3000aad9ce..a9f5cb686c 100644 --- a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp +++ b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp @@ -4097,6 +4097,9 @@ void tst_QLineEdit::clearButton() QTRY_COMPARE(filterModel->rowCount(), 1); // matches 'ab' QTest::mouseClick(clearButton, Qt::LeftButton, 0, QRect(QPoint(0, 0), clearButton->size()).center()); QTRY_COMPARE(filterModel->rowCount(), 3); + + filterLineEdit->setReadOnly(true); // QTBUG-34315 + QVERIFY(!clearButton->isEnabled()); } void tst_QLineEdit::sideWidgets() diff --git a/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp b/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp index 5b146cf443..b3e50b8ba8 100644 --- a/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp +++ b/tests/auto/widgets/widgets/qmdisubwindow/tst_qmdisubwindow.cpp @@ -954,9 +954,6 @@ void tst_QMdiSubWindow::mouseDoubleClick() QStyleOptionTitleBar options; options.initFrom(window); int height = window->style()->pixelMetric(QStyle::PM_TitleBarHeight, &options); - // ### Remove this after mac style has been fixed - if (window->style()->inherits("QMacStyle")) - height -= 4; // has border if (!window->style()->styleHint(QStyle::SH_TitleBar_NoBorder, &options, window)) height += window->isMinimized() ? 8 : 4; @@ -1692,11 +1689,6 @@ void tst_QMdiSubWindow::fixedMinMaxSize() QStyleOptionTitleBar options; options.initFrom(subWindow); int minimizedHeight = subWindow->style()->pixelMetric(QStyle::PM_TitleBarHeight, &options); -#if defined(Q_OS_MAC) && !defined(QT_NO_STYLE_MAC) - // ### Remove this after mac style has been fixed - if (subWindow->style()->inherits("QMacStyle")) - minimizedHeight -= 4; -#endif if (!subWindow->style()->styleHint(QStyle::SH_TitleBar_NoBorder, &options, subWindow)) minimizedHeight += 8; int minimizedWidth = subWindow->style()->pixelMetric(QStyle::PM_MDIMinimizedWidth, &options); diff --git a/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp b/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp index 7c1bb957d6..81ed983d0f 100644 --- a/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp +++ b/tests/auto/widgets/widgets/qmenu/tst_qmenu.cpp @@ -50,6 +50,7 @@ #include <QListWidget> #include <QWidgetAction> #include <QDesktopWidget> +#include <QScreen> #include <qdialog.h> #include <qmenu.h> @@ -59,6 +60,17 @@ Q_DECLARE_METATYPE(Qt::Key); Q_DECLARE_METATYPE(Qt::KeyboardModifiers); +static inline void centerOnScreen(QWidget *w, const QSize &size) +{ + const QPoint offset = QPoint(size.width() / 2, size.height() / 2); + w->move(QGuiApplication::primaryScreen()->availableGeometry().center() - offset); +} + +static inline void centerOnScreen(QWidget *w) +{ + centerOnScreen(w, w->geometry().size()); +} + class tst_QMenu : public QObject { Q_OBJECT @@ -257,9 +269,12 @@ void tst_QMenu::addActionsAndClear() void tst_QMenu::mouseActivation() { QWidget topLevel; + topLevel.resize(300, 200); + centerOnScreen(&topLevel); QMenu menu(&topLevel); topLevel.show(); menu.addAction("Menu Action"); + menu.move(topLevel.geometry().topRight() + QPoint(50, 0)); menu.show(); QTest::mouseClick(&menu, Qt::LeftButton, 0, menu.rect().center(), 300); QVERIFY(!menu.isVisible()); @@ -275,8 +290,10 @@ void tst_QMenu::mouseActivation() QMenu submenu("Menu"); submenu.addAction("action"); QAction *action = menubar.addMenu(&submenu); + menubar.move(topLevel.geometry().topRight() + QPoint(300, 0)); menubar.show(); + QTest::mouseClick(&menubar, Qt::LeftButton, 0, menubar.actionGeometry(action).center(), 300); QVERIFY(submenu.isVisible()); QTest::mouseClick(&submenu, Qt::LeftButton, 0, QPoint(5, 5), 300); @@ -378,13 +395,16 @@ void tst_QMenu::focus() #endif QWidget window; + window.resize(300, 200); QPushButton button("Push me", &window); + centerOnScreen(&window); window.show(); qApp->setActiveWindow(&window); QVERIFY(button.hasFocus()); QCOMPARE(QApplication::focusWidget(), (QWidget *)&button); QCOMPARE(QApplication::activeWindow(), &window); + menu.move(window.geometry().topRight() + QPoint(50, 0)); menu.show(); QVERIFY(button.hasFocus()); QCOMPARE(QApplication::focusWidget(), (QWidget *)&button); @@ -399,6 +419,8 @@ void tst_QMenu::overrideMenuAction() { //test the override menu action by first creating an action to which we set its menu QMainWindow w; + w.resize(300, 200); + centerOnScreen(&w); QAction *aFileMenu = new QAction("&File", &w); w.menuBar()->addAction(aFileMenu); @@ -442,6 +464,8 @@ void tst_QMenu::statusTip() { //check that the statustip of actions inserted into the menu are displayed QMainWindow w; + w.resize(300, 200); + centerOnScreen(&w); connect(w.statusBar(), SIGNAL(messageChanged(QString)), SLOT(onStatusMessageChanged(QString)));; //creates the status bar QToolBar tb; QAction a("main action", &tb); @@ -540,10 +564,12 @@ void tst_QMenu::tearOff() menu->addAction("bbb"); QVERIFY(menu->isTearOffEnabled()); + widget.resize(300, 200); + centerOnScreen(&widget); widget.show(); widget.activateWindow(); QVERIFY(QTest::qWaitForWindowActive(&widget)); - menu->popup(QPoint(0,0)); + menu->popup(widget.geometry().topRight() + QPoint(50, 0)); QVERIFY(QTest::qWaitForWindowActive(menu)); QVERIFY(!menu->isTearOffMenuVisible()); @@ -568,14 +594,18 @@ void tst_QMenu::layoutDirection() { QMainWindow win; win.setLayoutDirection(Qt::RightToLeft); + win.resize(300, 200); + centerOnScreen(&win); QMenu menu(&win); + menu.move(win.geometry().topRight() + QPoint(50, 0)); menu.show(); QVERIFY(QTest::qWaitForWindowExposed(&menu)); QCOMPARE(menu.layoutDirection(), Qt::RightToLeft); menu.close(); menu.setParent(0); + menu.move(win.geometry().topRight() + QPoint(50, 0)); menu.show(); QVERIFY(QTest::qWaitForWindowExposed(&menu)); QCOMPARE(menu.layoutDirection(), QApplication::layoutDirection()); @@ -702,6 +732,7 @@ void tst_QMenu::task256918_setFont() QFont f; f.setPointSize(30); action->setFont(f); + centerOnScreen(&menu, QSize(120, 40)); menu.show(); //ensures that the actiongeometry are calculated QVERIFY(menu.actionGeometry(action).height() > f.pointSize()); } @@ -830,6 +861,13 @@ void PopulateOnAboutToShowTestMenu::populateMenu() addSeparator(); } +static inline QByteArray msgGeometryIntersects(const QRect &r1, const QRect &r2) +{ + QString result; + QDebug(&result) << r1 << "intersects" << r2; + return result.toLocal8Bit(); +} + void tst_QMenu::pushButtonPopulateOnAboutToShow() { QPushButton b("Test PushButton"); @@ -842,7 +880,7 @@ void tst_QMenu::pushButtonPopulateOnAboutToShow() const QRect screen = QApplication::desktop()->screenGeometry(scrNumber); QRect desiredGeometry = b.geometry(); - desiredGeometry.moveTopLeft(QPoint(10, screen.bottom()-b.height()-5)); + desiredGeometry.moveTopLeft(QPoint(screen.x() + 10, screen.bottom() - b.height() - 5)); b.setGeometry(desiredGeometry); QVERIFY(QTest::qWaitForWindowExposed(&b)); @@ -859,13 +897,13 @@ void tst_QMenu::pushButtonPopulateOnAboutToShow() QTimer::singleShot(300, buttonMenu, SLOT(hide())); QTest::mouseClick(&b, Qt::LeftButton, Qt::NoModifier, b.rect().center()); - QVERIFY(!buttonMenu->geometry().intersects(b.geometry())); + QVERIFY2(!buttonMenu->geometry().intersects(b.geometry()), msgGeometryIntersects(buttonMenu->geometry(), b.geometry())); // note: we're assuming that, if we previously got the desired geometry, we'll get it here too b.move(10, screen.bottom()-buttonMenu->height()-5); QTimer::singleShot(300, buttonMenu, SLOT(hide())); QTest::mouseClick(&b, Qt::LeftButton, Qt::NoModifier, b.rect().center()); - QVERIFY(!buttonMenu->geometry().intersects(b.geometry())); + QVERIFY2(!buttonMenu->geometry().intersects(b.geometry()), msgGeometryIntersects(buttonMenu->geometry(), b.geometry())); } void tst_QMenu::QTBUG7907_submenus_autoselect() @@ -878,6 +916,7 @@ void tst_QMenu::QTBUG7907_submenus_autoselect() set1.addMenu(&subset); menu.addMenu(&set1); menu.addMenu(&set2); + centerOnScreen(&menu, QSize(120, 100)); menu.show(); QVERIFY(QTest::qWaitForWindowExposed(&menu)); QTest::mouseClick(&menu, Qt::LeftButton, Qt::NoModifier, QPoint(5,5) ); @@ -893,6 +932,7 @@ void tst_QMenu::QTBUG7411_submenus_activate() sub1.addAction("foo"); sub1.setTitle("&sub1"); QAction *act1 = menu.addMenu(&sub1); + centerOnScreen(&menu, QSize(120, 100)); menu.show(); QVERIFY(QTest::qWaitForWindowExposed(&menu)); menu.setActiveAction(act); @@ -911,12 +951,12 @@ void tst_QMenu::QTBUG30595_rtl_submenu() sub.addAction("bar"); sub.setTitle("&sub"); menu.addMenu(&sub); - menu.move(200, 20); + centerOnScreen(&menu, QSize(120, 40)); menu.show(); QVERIFY(QTest::qWaitForWindowExposed(&menu)); QTest::mouseClick(&menu, Qt::LeftButton, Qt::NoModifier, QPoint(5,5) ); QTRY_VERIFY(sub.isVisible()); - QVERIFY(sub.pos().x() < menu.pos().x()); + QVERIFY2(sub.pos().x() < menu.pos().x(), QByteArray::number(sub.pos().x()) + QByteArrayLiteral(" not less than ") + QByteArray::number(menu.pos().x())); } void tst_QMenu::QTBUG20403_nested_popup_on_shortcut_trigger() @@ -927,6 +967,7 @@ void tst_QMenu::QTBUG20403_nested_popup_on_shortcut_trigger() subsub1.addAction("foo"); sub1.addMenu(&subsub1); menu.addMenu(&sub1); + centerOnScreen(&menu, QSize(120, 100)); menu.show(); QVERIFY(QTest::qWaitForWindowExposed(&menu)); QTest::keyPress(&menu, Qt::Key_S); diff --git a/tests/auto/xml/sax/qxmlsimplereader/tst_qxmlsimplereader.cpp b/tests/auto/xml/sax/qxmlsimplereader/tst_qxmlsimplereader.cpp index f09fbff6c4..ed909946e6 100644 --- a/tests/auto/xml/sax/qxmlsimplereader/tst_qxmlsimplereader.cpp +++ b/tests/auto/xml/sax/qxmlsimplereader/tst_qxmlsimplereader.cpp @@ -160,6 +160,7 @@ class tst_QXmlSimpleReader : public QObject void reportNamespace() const; void reportNamespace_data() const; void roundtripWithNamespaces() const; + void dtdRecursionLimit(); private: static QDomDocument fromByteArray(const QString &title, const QByteArray &ba, bool *ok); @@ -755,5 +756,62 @@ void tst_QXmlSimpleReader::roundtripWithNamespaces() const } } +class TestHandler : public QXmlDefaultHandler +{ +public: + TestHandler() : + recursionCount(0) + { + } + + bool internalEntityDecl(const QString &name, const QString &value) + { + ++recursionCount; + return QXmlDefaultHandler::internalEntityDecl(name, value); + } + + int recursionCount; +}; + +void tst_QXmlSimpleReader::dtdRecursionLimit() +{ + QFile file("xmldocs/2-levels-nested-dtd.xml"); + QVERIFY(file.open(QIODevice::ReadOnly)); + QXmlSimpleReader xmlReader; + { + QXmlInputSource *source = new QXmlInputSource(&file); + TestHandler handler; + xmlReader.setDeclHandler(&handler); + xmlReader.setErrorHandler(&handler); + QVERIFY(!xmlReader.parse(source)); + } + + file.close(); + file.setFileName("xmldocs/1-levels-nested-dtd.xml"); + QVERIFY(file.open(QIODevice::ReadOnly)); + { + QXmlInputSource *source = new QXmlInputSource(&file); + TestHandler handler; + xmlReader.setDeclHandler(&handler); + xmlReader.setErrorHandler(&handler); + QVERIFY(!xmlReader.parse(source)); + // The error wasn't because of the recursion limit being reached, + // it was because the document is not valid. + QVERIFY(handler.recursionCount < 2); + } + + file.close(); + file.setFileName("xmldocs/internal-entity-polynomial-attribute.xml"); + QVERIFY(file.open(QIODevice::ReadOnly)); + { + QXmlInputSource *source = new QXmlInputSource(&file); + TestHandler handler; + xmlReader.setDeclHandler(&handler); + xmlReader.setErrorHandler(&handler); + QVERIFY(!xmlReader.parse(source)); + QCOMPARE(handler.recursionCount, 2); + } +} + QTEST_MAIN(tst_QXmlSimpleReader) #include "tst_qxmlsimplereader.moc" diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/1-levels-nested-dtd.xml b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/1-levels-nested-dtd.xml new file mode 100644 index 0000000000..0dfc15b165 --- /dev/null +++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/1-levels-nested-dtd.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!-- Test non-deterministic content model matching. + +Entity references are not part of the internal DTD subset (for good reason). + +--> +<!DOCTYPE root [ +<!ELEMENT e0 EMPTY> +<!ENTITY % e1 "(e0,e0)"> +<!ELEMENT root (%e1;)?> +]> +<root/>
\ No newline at end of file diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/2-levels-nested-dtd.xml b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/2-levels-nested-dtd.xml new file mode 100644 index 0000000000..7ec06db85f --- /dev/null +++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/2-levels-nested-dtd.xml @@ -0,0 +1,13 @@ +<?xml version="1.0"?> +<!-- Test non-deterministic content model matching. + +Entity references are not part of the internal DTD subset (for good reason). + +--> +<!DOCTYPE root [ +<!ELEMENT e0 EMPTY> +<!ENTITY % e1 "(e0,e0)"> +<!ENTITY % e2 "(%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;,%e1;)"> +<!ELEMENT root (%e2;)?> +]> +<root/> diff --git a/tests/auto/xml/sax/qxmlsimplereader/xmldocs/internal-entity-polynomial-attribute.xml b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/internal-entity-polynomial-attribute.xml new file mode 100644 index 0000000000..bbb88f39f6 --- /dev/null +++ b/tests/auto/xml/sax/qxmlsimplereader/xmldocs/internal-entity-polynomial-attribute.xml @@ -0,0 +1,13 @@ +<?xml version="1.0"?> +<!-- Test polynomial growth of expanded XML. + Expansion happens in an attribute. --> +<!DOCTYPE root [ +<!ELEMENT root EMPTY> +<!ATTLIST root id CDATA #IMPLIED> +<!ENTITY e1 "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"> +<!ENTITY e2 "&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;&e1;"> +<!ENTITY e3 "&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;&e2;"> +<!ENTITY e4 "&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;&e3;"> +]> +<root id="&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;&e4;"/> + diff --git a/tests/benchmarks/corelib/io/qprocess/testProcessLoopback/testProcessLoopback.pro b/tests/benchmarks/corelib/io/qprocess/testProcessLoopback/testProcessLoopback.pro index 3940ddbf98..8fd4db6b4b 100644 --- a/tests/benchmarks/corelib/io/qprocess/testProcessLoopback/testProcessLoopback.pro +++ b/tests/benchmarks/corelib/io/qprocess/testProcessLoopback/testProcessLoopback.pro @@ -1,5 +1,6 @@ SOURCES = main.cpp CONFIG -= qt app_bundle CONFIG += console +winrt: QMAKE_LFLAGS += /ENTRY:mainCRTStartup DESTDIR = ./ DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/benchmarks/corelib/thread/qmutex/tst_qmutex.cpp b/tests/benchmarks/corelib/thread/qmutex/tst_qmutex.cpp index 37fa571f8c..52c60f9484 100644 --- a/tests/benchmarks/corelib/thread/qmutex/tst_qmutex.cpp +++ b/tests/benchmarks/corelib/thread/qmutex/tst_qmutex.cpp @@ -88,7 +88,9 @@ void NativeMutexUnlock(NativeMutexType *mutex) } #endif #elif defined(Q_OS_WIN) -# define _WIN32_WINNT 0x0400 +# ifndef Q_OS_WINRT +# define _WIN32_WINNT 0x0400 +# endif # include <windows.h> typedef CRITICAL_SECTION NativeMutexType; void NativeMutexInitialize(NativeMutexType *mutex) diff --git a/tests/manual/cocoa/qt_on_cocoa/main.mm b/tests/manual/cocoa/qt_on_cocoa/main.mm index c9338f25f4..9a39788b02 100644 --- a/tests/manual/cocoa/qt_on_cocoa/main.mm +++ b/tests/manual/cocoa/qt_on_cocoa/main.mm @@ -44,7 +44,7 @@ #include <QtWidgets/QtWidgets> #include <private/qwidgetwindow_qpa_p.h> -#include <QtGui/qplatformnativeinterface_qpa.h> +#include <QtGui/qpa/qplatformnativeinterface.h> #include <QtGui/QPixmap> diff --git a/tests/manual/dialogs/dialogs.pro b/tests/manual/dialogs/dialogs.pro index d19c3026d0..71c41119fe 100644 --- a/tests/manual/dialogs/dialogs.pro +++ b/tests/manual/dialogs/dialogs.pro @@ -1,10 +1,10 @@ QT += core gui -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport TARGET = dialogs TEMPLATE = app SOURCES += main.cpp filedialogpanel.cpp colordialogpanel.cpp fontdialogpanel.cpp \ - wizardpanel.cpp messageboxpanel.cpp + wizardpanel.cpp messageboxpanel.cpp printdialogpanel.cpp utils.cpp HEADERS += filedialogpanel.h colordialogpanel.h fontdialogpanel.h \ - wizardpanel.h messageboxpanel.h + wizardpanel.h messageboxpanel.h printdialogpanel.h utils.h diff --git a/tests/manual/dialogs/filedialogpanel.cpp b/tests/manual/dialogs/filedialogpanel.cpp index e234835cdb..2ae6241849 100644 --- a/tests/manual/dialogs/filedialogpanel.cpp +++ b/tests/manual/dialogs/filedialogpanel.cpp @@ -40,6 +40,7 @@ ****************************************************************************/ #include "filedialogpanel.h" +#include "utils.h" #include <QGridLayout> #include <QVBoxLayout> @@ -48,7 +49,6 @@ #include <QFormLayout> #include <QSpacerItem> #include <QGroupBox> -#include <QComboBox> #include <QPushButton> #include <QCheckBox> #include <QLineEdit> @@ -60,25 +60,19 @@ #include <QTimer> #include <QDebug> -struct ComboData -{ - const char *description; - int value; -}; - -const ComboData acceptModeComboData[] = +const FlagData acceptModeComboData[] = { {"AcceptOpen", QFileDialog::AcceptOpen }, {"AcceptSave", QFileDialog::AcceptSave } }; -const ComboData viewModeComboData[] = +const FlagData viewModeComboData[] = { {"Detail", QFileDialog::Detail}, {"List", QFileDialog::List} }; -const ComboData fileModeComboData[] = +const FlagData fileModeComboData[] = { {"AnyFile", QFileDialog::AnyFile}, {"ExistingFile", QFileDialog::ExistingFile}, @@ -87,25 +81,6 @@ const ComboData fileModeComboData[] = {"DirectoryOnly", QFileDialog::DirectoryOnly} }; -static QComboBox *createCombo(QWidget *parent, const ComboData *d, size_t size) -{ - QComboBox *c = new QComboBox(parent); - for (size_t i = 0; i < size; ++i) - c->addItem(QLatin1String(d[i].description), QVariant(d[i].value)); - return c; -} - -template <class Enum> -Enum comboBoxValue(const QComboBox *c) -{ - return static_cast<Enum>(c->itemData(c->currentIndex()).toInt()); -} - -inline void setComboBoxValue(QComboBox *c, int v) -{ - c->setCurrentIndex(c->findData(QVariant(v))); -} - static inline QPushButton *addButton(const QString &description, QGridLayout *layout, int &row, int column, QObject *receiver, const char *slotFunc) { @@ -155,9 +130,9 @@ FileDialogPanel::FileDialogPanel(QWidget *parent) , m_resolveSymLinks(new QCheckBox(tr("Resolve symlinks"))) , m_native(new QCheckBox(tr("Use native dialog"))) , m_customDirIcons(new QCheckBox(tr("Don't use custom directory icons"))) - , m_acceptMode(createCombo(this, acceptModeComboData, sizeof(acceptModeComboData)/sizeof(ComboData))) - , m_fileMode(createCombo(this, fileModeComboData, sizeof(fileModeComboData)/sizeof(ComboData))) - , m_viewMode(createCombo(this, viewModeComboData, sizeof(viewModeComboData)/sizeof(ComboData))) + , m_acceptMode(createCombo(this, acceptModeComboData, sizeof(acceptModeComboData)/sizeof(FlagData))) + , m_fileMode(createCombo(this, fileModeComboData, sizeof(fileModeComboData)/sizeof(FlagData))) + , m_viewMode(createCombo(this, viewModeComboData, sizeof(viewModeComboData)/sizeof(FlagData))) , m_allowedSchemes(new QLineEdit(this)) , m_defaultSuffix(new QLineEdit(this)) , m_directory(new QLineEdit(this)) @@ -355,6 +330,7 @@ void FileDialogPanel::getOpenFileNames() void FileDialogPanel::getOpenFileUrls() { +#if QT_VERSION >= 0x050000 QString selectedFilter = m_selectedNameFilter->text().trimmed(); const QList<QUrl> files = QFileDialog::getOpenFileUrls(this, tr("getOpenFileNames Qt %1").arg(QLatin1String(QT_VERSION_STR)), @@ -367,6 +343,7 @@ void FileDialogPanel::getOpenFileUrls() << "\nName filter: " << selectedFilter; QMessageBox::information(this, tr("getOpenFileNames"), result, QMessageBox::Ok); } +#endif // Qt 5 } void FileDialogPanel::getOpenFileName() @@ -386,6 +363,7 @@ void FileDialogPanel::getOpenFileName() void FileDialogPanel::getOpenFileUrl() { +#if QT_VERSION >= 0x050000 QString selectedFilter = m_selectedNameFilter->text().trimmed(); const QUrl file = QFileDialog::getOpenFileUrl(this, tr("getOpenFileUrl Qt %1").arg(QLatin1String(QT_VERSION_STR)), @@ -398,6 +376,7 @@ void FileDialogPanel::getOpenFileUrl() << "\nName filter: " << selectedFilter; QMessageBox::information(this, tr("getOpenFileName"), result, QMessageBox::Ok); } +#endif // Qt 5 } void FileDialogPanel::getSaveFileName() @@ -417,6 +396,7 @@ void FileDialogPanel::getSaveFileName() void FileDialogPanel::getSaveFileUrl() { +#if QT_VERSION >= 0x050000 QString selectedFilter = m_selectedNameFilter->text().trimmed(); const QUrl file = QFileDialog::getSaveFileUrl(this, tr("getSaveFileName Qt %1").arg(QLatin1String(QT_VERSION_STR)), @@ -429,6 +409,7 @@ void FileDialogPanel::getSaveFileUrl() << "\nName filter: " << selectedFilter; QMessageBox::information(this, tr("getSaveFileNames"), result, QMessageBox::Ok); } +#endif // Qt 5 } void FileDialogPanel::getExistingDirectory() @@ -442,12 +423,14 @@ void FileDialogPanel::getExistingDirectory() void FileDialogPanel::getExistingDirectoryUrl() { +#if QT_VERSION >= 0x050000 const QUrl dir = QFileDialog::getExistingDirectoryUrl(this, tr("getExistingDirectory Qt %1").arg(QLatin1String(QT_VERSION_STR)), QUrl(m_directory->text()), options() | QFileDialog::ShowDirsOnly, allowedSchemes()); if (!dir.isEmpty()) QMessageBox::information(this, tr("getExistingDirectory"), QLatin1String("Directory: ") + dir.toString(), QMessageBox::Ok); +#endif // Qt 5 } void FileDialogPanel::restoreDefaults() @@ -493,9 +476,11 @@ void FileDialogPanel::applySettings(QFileDialog *d) const if (!filter.isEmpty()) d->selectNameFilter(filter); } else { +#if QT_VERSION >= 0x050000 d->setMimeTypeFilters(filters); if (!filter.isEmpty()) d->selectMimeTypeFilter(filter); +#endif // Qt 5 } foreach (LabelLineEdit *l, m_labelLineEdits) l->apply(d); diff --git a/tests/manual/dialogs/fontdialogpanel.cpp b/tests/manual/dialogs/fontdialogpanel.cpp index c72bf77351..ff45402197 100644 --- a/tests/manual/dialogs/fontdialogpanel.cpp +++ b/tests/manual/dialogs/fontdialogpanel.cpp @@ -209,10 +209,12 @@ void FontDialogPanel::applySettings(QFontDialog *d) const { d->setOption(QFontDialog::NoButtons, m_noButtons->isChecked()); d->setOption(QFontDialog::DontUseNativeDialog, m_dontUseNativeDialog->isChecked()); +#if QT_VERSION >= 0x050000 d->setOption(QFontDialog::ScalableFonts, m_scalableFilter->isChecked()); d->setOption(QFontDialog::NonScalableFonts, m_nonScalableFilter->isChecked()); d->setOption(QFontDialog::MonospacedFonts, m_monospacedFilter->isChecked()); d->setOption(QFontDialog::ProportionalFonts, m_proportionalFilter->isChecked()); +#endif // Qt 5 QFont font = m_fontFamilyBox->currentFont(); font.setPointSizeF(m_fontSizeBox->value()); diff --git a/tests/manual/dialogs/main.cpp b/tests/manual/dialogs/main.cpp index c5f14cabef..6082727c3b 100644 --- a/tests/manual/dialogs/main.cpp +++ b/tests/manual/dialogs/main.cpp @@ -42,6 +42,7 @@ #include "filedialogpanel.h" #include "colordialogpanel.h" #include "fontdialogpanel.h" +#include "printdialogpanel.h" #include "wizardpanel.h" #include "messageboxpanel.h" @@ -75,6 +76,9 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) tabWidget->addTab(new FontDialogPanel, tr("QFontDialog")); tabWidget->addTab(new WizardPanel, tr("QWizard")); tabWidget->addTab(new MessageBoxPanel, tr("QMessageBox")); +#ifndef QT_NO_PRINTER + tabWidget->addTab(new PrintDialogPanel, tr("QPrintDialog")); +#endif setCentralWidget(tabWidget); } diff --git a/tests/manual/dialogs/messageboxpanel.cpp b/tests/manual/dialogs/messageboxpanel.cpp index 529a8251e1..ced582981e 100644 --- a/tests/manual/dialogs/messageboxpanel.cpp +++ b/tests/manual/dialogs/messageboxpanel.cpp @@ -149,9 +149,11 @@ void MessageBoxPanel::setupMessageBox(QMessageBox &box) if (box.standardButtons() == (QMessageBox::StandardButtons) 0) box.setStandardButtons(QMessageBox::Ok); // just to have something. +#if QT_VERSION >= 0x050000 box.setCheckBox(0); if (m_checkboxText->text().length() > 0) box.setCheckBox(new QCheckBox(m_checkboxText->text())); +#endif // Qt 5 box.setIcon((QMessageBox::Icon) m_iconComboBox->currentIndex()); } @@ -176,12 +178,14 @@ void MessageBoxPanel::doExec() QString sres; sres.setNum(res, 16); m_resultLabel->setText(QString::fromLatin1("Return value (hex): %1").arg(sres)); +#if QT_VERSION >= 0x050000 if (m_msgbox->checkBox()) { if (m_msgbox->checkBox()->isChecked()) m_checkBoxResult->setText(QString::fromLatin1("Checkbox was checked")); else m_checkBoxResult->setText(QString::fromLatin1("Checkbox was not checked")); } +#endif // Qt 5 } void MessageBoxPanel::doShowApply() diff --git a/tests/manual/dialogs/printdialogpanel.cpp b/tests/manual/dialogs/printdialogpanel.cpp new file mode 100644 index 0000000000..02beaa4bae --- /dev/null +++ b/tests/manual/dialogs/printdialogpanel.cpp @@ -0,0 +1,417 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT_NO_PRINTER + +#include "printdialogpanel.h" +#include "utils.h" + +#include <QPrinter> +#include <QPrintDialog> +#include <QPrintPreviewDialog> +#include <QApplication> +#include <QDesktopWidget> +#include <QGroupBox> +#include <QCheckBox> +#include <QLabel> +#include <QPushButton> +#include <QGridLayout> +#include <QFormLayout> +#include <QVBoxLayout> +#include <QDoubleSpinBox> +#include <QPainter> +#include <QFont> +#include <QFontMetrics> +#include <QDateTime> +#include <QDebug> +#include <QTextStream> + +const FlagData modeComboData[] = +{ + {"ScreenResolution", QPrinter::ScreenResolution}, + {"PrinterResolution", QPrinter::PrinterResolution}, + {"HighResolution", QPrinter::HighResolution} +}; + +const FlagData orientationComboData[] = +{ + {"Portrait", QPrinter::Portrait}, + {"Landscape", QPrinter::Landscape}, +}; + +const FlagData pageSizeComboData[] = +{ + {"A4", QPrinter::A4}, + {"B5", QPrinter::B5}, + {"Letter", QPrinter::Letter}, + {"Legal", QPrinter::Legal}, + {"Executive", QPrinter::Executive}, + {"A0", QPrinter::A0}, + {"A1", QPrinter::A1}, + {"A2", QPrinter::A2}, + {"A3", QPrinter::A3}, + {"A5", QPrinter::A5}, + {"A6", QPrinter::A6}, + {"A7", QPrinter::A7}, + {"A8", QPrinter::A8}, + {"A9", QPrinter::A9}, + {"B0", QPrinter::B0}, + {"B1", QPrinter::B1}, + {"B10", QPrinter::B10}, + {"B2", QPrinter::B2}, + {"B3", QPrinter::B3}, + {"B4", QPrinter::B4}, + {"B6", QPrinter::B6}, + {"B7", QPrinter::B7}, + {"B8", QPrinter::B8}, + {"B9", QPrinter::B9}, + {"C5E", QPrinter::C5E}, + {"Comm10E", QPrinter::Comm10E}, + {"DLE", QPrinter::DLE}, + {"Folio", QPrinter::Folio}, + {"Ledger", QPrinter::Ledger}, + {"Tabloid", QPrinter::Tabloid}, + {"Custom", QPrinter::Custom} +}; + +const FlagData printDialogOptions[] = +{ + {"PrintToFile", QPrintDialog::PrintToFile}, + {"PrintSelection", QPrintDialog::PrintSelection}, + {"PrintPageRange", QPrintDialog::PrintPageRange}, + {"PrintShowPageSize", QPrintDialog::PrintShowPageSize}, + {"PrintCollateCopies", QPrintDialog::PrintCollateCopies}, + {"PrintCurrentPage", QPrintDialog::PrintCurrentPage} +}; + +const FlagData printRangeOptions[] = +{ + {"AllPages", QPrintDialog::AllPages}, + {"Selection", QPrintDialog::Selection}, + {"PageRange", QPrintDialog::PageRange}, + {"CurrentPage", QPrintDialog::CurrentPage} +}; + +QTextStream &operator<<(QTextStream &s, const QSizeF &size) +{ + s << size.width() << 'x' << size.height(); + return s; +} + +QTextStream &operator<<(QTextStream &s, const QRectF &rect) +{ + s << rect.width() << 'x' << rect.height() << forcesign << rect.x() << rect.y() << noforcesign; + return s; +} + +QTextStream &operator<<(QTextStream &s, const QPrinter &printer) +{ + s << '"' << printer.printerName() << "\"\nPaper #" <<printer.paperSize() +#if QT_VERSION >= 0x050000 + << " \"" << printer.paperName() << '"' +#endif + << (printer.orientation() == QPrinter::Portrait ? ", Portrait" : ", Landscape"); + if (printer.fullPage()) + s << ", full page"; + s << "\nPaper size: " + << printer.paperSize(QPrinter::Point) << "pt " + << printer.paperSize(QPrinter::Millimeter) << "mm " + << "\n " << printer.paperSize(QPrinter::DevicePixel) << "device pt " + << printer.paperSize(QPrinter::Inch) << "inch " +#if QT_VERSION >= 0x050000 + << "\nPagedPaintDevSize: " << printer.pageSizeMM() << "mm" +#endif + << "\nLogical resolution : " << printer.logicalDpiX() << ',' << printer.logicalDpiY() << "DPI" + << "\nPhysical resolution: " << printer.physicalDpiX() << ',' << printer.physicalDpiY() << "DPI" + << "\nPaperRect: " << printer.paperRect(QPrinter::Point) << "pt " + << printer.paperRect(QPrinter::Millimeter) << "mm " + << "\n " << printer.paperRect(QPrinter::DevicePixel) << "device pt" + << "\nPageRect: " << printer.pageRect(QPrinter::Point) << "pt " + << printer.pageRect(QPrinter::Millimeter) << "mm " + << "\n " << printer.pageRect(QPrinter::DevicePixel) << "device pt"; + return s; +} + +// Print a page with a rectangular frame, vertical / horizontal rulers in cm and printer info. + +static void drawHorizCmRuler(QPainter &painter, int x1, int x2, int y) +{ + painter.drawLine(x1, y, x2, y); + const int dpI = painter.device()->logicalDpiX(); + const int dpCm = qRound(double(dpI) / 2.54); + const int h = dpCm / 2; + const QFontMetrics fm(painter.font()); + for (int cm = 0, x = x1; x < x2; x += dpCm, ++cm) { + painter.drawLine(x, y, x, y - h); + if (cm) { + const QString n = QString::number(cm); + const QRect br = fm.boundingRect(n); + painter.drawText(x - br.width() / 2, y - h - 10, n); + } + } +} + +static void drawVertCmRuler(QPainter &painter, int x, int y1, int y2) +{ + painter.drawLine(x, y1, x, y2); + const int dpI = painter.device()->logicalDpiY(); + const int dpCm = qRound(double(dpI) / 2.54); + const int h = dpCm / 2; + const QFontMetrics fm(painter.font()); + for (int cm = 0, y = y1; y < y2; y += dpCm, ++cm) { + painter.drawLine(x, y, x + h, y); + if (cm) { + const QString n = QString::number(cm); + const QRect br = fm.boundingRect(n); + painter.drawText(x + h + 10, y + br.height() / 2, n); + } + } +} + +static void print(QPrinter *printer) +{ + QPainter painter(printer); + const QRectF pageF = printer->pageRect(); + + painter.drawRect(pageF); + + drawHorizCmRuler(painter, pageF.x(), pageF.right(), pageF.height() /2); + drawVertCmRuler(painter, pageF.x() + pageF.width() / 2, pageF.top(), pageF.bottom()); + + QFont font = painter.font(); + font.setFamily("Courier"); + font.setPointSize(10); + painter.setFont(font); + + // Format message. + const int charHeight = QFontMetrics(font).boundingRect('X').height(); + QString msg; + QTextStream str(&msg); + str << "Qt "<< QT_VERSION_STR; +#if QT_VERSION >= 0x050000 + str << ' ' << QGuiApplication::platformName(); +#endif + str << ' ' << QDateTime::currentDateTime().toString() + << "\nFont: " << font.family() << ' ' << font.pointSize() << '\n' + << *printer; + + QPointF textPoint = pageF.topLeft() + QPoint(10, charHeight + 10); + foreach (const QString &line, msg.split('\n')) { + painter.drawText(textPoint, line); + textPoint.ry() += (15 * charHeight) / 10; + } + + painter.end(); +} + +class PrintPreviewDialog : public QPrintPreviewDialog { + Q_OBJECT +public: + explicit PrintPreviewDialog(QPrinter *printer, QWidget *parent = 0) : QPrintPreviewDialog(printer, parent) + { + connect(this, SIGNAL(paintRequested(QPrinter*)), this, SLOT(slotPaintRequested(QPrinter*))); + } + +public slots: + void slotPaintRequested(QPrinter *p) { print(p); } +}; + +class PageSizeControl : public QWidget { +public: + explicit PageSizeControl(QWidget *parent = 0); + QSizeF pageSize() const { return QSizeF(m_width->value(), m_height->value()); } + void setPageSize(const QSizeF &s) { m_width->setValue(s.width()); m_height->setValue(s.height()); } + +private: + QDoubleSpinBox *m_width; + QDoubleSpinBox *m_height; +}; + +PageSizeControl::PageSizeControl(QWidget *parent) + : QWidget(parent) + , m_width(new QDoubleSpinBox(this)) + , m_height(new QDoubleSpinBox(this)) +{ + m_width->setRange(1, 1000); + m_width->setSingleStep(10); + m_height->setRange(1, 1000); + m_height->setSingleStep(10); + QHBoxLayout *hBoxLayout = new QHBoxLayout(this); + hBoxLayout->addWidget(m_width); + hBoxLayout->addWidget(new QLabel("x", this)); + hBoxLayout->addWidget(m_height); + hBoxLayout->addWidget(new QLabel("mm", this)); +} + +PrintDialogPanel::PrintDialogPanel(QWidget *parent) + : QWidget(parent) + , m_creationGroupBox(new QGroupBox(tr("Create"), this)) + , m_settingsGroupBox(new QGroupBox(tr("Settings"), this)) + , m_dialogsGroupBox(new QGroupBox(tr("Dialogs"), this)) + , m_pageSizeCombo(new QComboBox) +{ + // Create with resolution + QHBoxLayout *hBoxLayout = new QHBoxLayout(m_creationGroupBox); + m_modeCombo = createCombo(m_creationGroupBox, modeComboData, sizeof(modeComboData)/sizeof(FlagData)); + hBoxLayout->addWidget(m_modeCombo); + m_createButton = new QPushButton(tr("Create"), m_creationGroupBox); + connect(m_createButton, SIGNAL(clicked()), this, SLOT(createPrinter())); + hBoxLayout->addWidget(m_createButton); + m_deleteButton = new QPushButton(tr("Delete"), m_creationGroupBox); + connect(m_deleteButton, SIGNAL(clicked()), this, SLOT(deletePrinter())); + hBoxLayout->addWidget(m_deleteButton); + hBoxLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored)); + + QFormLayout *formLayout = new QFormLayout(m_settingsGroupBox); + m_pageSizeCombo = createCombo(m_settingsGroupBox, pageSizeComboData, sizeof(pageSizeComboData)/sizeof(FlagData)); + connect(m_pageSizeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(enableCustomSizeControl())); + formLayout->addRow(tr("Paper #:"), m_pageSizeCombo); + m_customPageSizeControl = new PageSizeControl; + formLayout->addRow(tr("Custom size:"), m_customPageSizeControl); + m_orientationCombo = createCombo(m_settingsGroupBox, orientationComboData, sizeof(orientationComboData)/sizeof(FlagData)); + formLayout->addRow("Orientation:", m_orientationCombo); + m_fullPageCheckBox = new QCheckBox(tr("Full page"), m_settingsGroupBox); + formLayout->addRow(m_fullPageCheckBox); + + QVBoxLayout *vBoxLayout = new QVBoxLayout(m_dialogsGroupBox); + + m_printDialogOptionsControl = new OptionsControl(tr("Options"), printDialogOptions, sizeof(printDialogOptions) / sizeof(FlagData), m_dialogsGroupBox); + vBoxLayout->addWidget(m_printDialogOptionsControl); + m_printDialogRangeCombo = createCombo(m_dialogsGroupBox, printRangeOptions, sizeof(printRangeOptions) / sizeof(FlagData)); + vBoxLayout->addWidget(m_printDialogRangeCombo); + + { + QPrintDialog dialog; + m_printDialogOptionsControl->setValue(dialog.options()); + m_printDialogRangeCombo->setCurrentIndex(dialog.printRange()); + } + + QPushButton *button = new QPushButton(tr("Print..."), m_dialogsGroupBox); + connect(button, SIGNAL(clicked()), this, SLOT(showPrintDialog())); + vBoxLayout->addWidget(button); + button = new QPushButton(tr("Preview..."), m_dialogsGroupBox); + connect(button, SIGNAL(clicked()), this, SLOT(showPreviewDialog())); + vBoxLayout->addWidget(button); + + QGridLayout *gridLayout = new QGridLayout(this); + gridLayout->addWidget(m_creationGroupBox, 0, 0); + gridLayout->addWidget(m_settingsGroupBox, 1, 0); + gridLayout->addWidget(m_dialogsGroupBox, 0, 1, 2, 1); + gridLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 2, 0, 1, 2); + + enablePanels(); +} + +PrintDialogPanel::~PrintDialogPanel() +{ +} + +void PrintDialogPanel::enablePanels() +{ + const bool exists = !m_printer.isNull(); + m_createButton->setEnabled(!exists); + m_modeCombo->setEnabled(!exists); + m_deleteButton->setEnabled(exists); + m_settingsGroupBox->setEnabled(exists); + m_dialogsGroupBox->setEnabled(exists); +} + +void PrintDialogPanel::createPrinter() +{ + const QPrinter::PrinterMode mode = comboBoxValue<QPrinter::PrinterMode>(m_modeCombo); + m_printer.reset(new QPrinter(mode)); // Can set only once. + retrieveSettings(m_printer.data()); + enablePanels(); + enableCustomSizeControl(); +} + +void PrintDialogPanel::deletePrinter() +{ + m_printer.reset(); + enablePanels(); +} + +void PrintDialogPanel::applySettings(QPrinter *printer) const +{ + const QPrinter::PageSize pageSize = comboBoxValue<QPrinter::PageSize>(m_pageSizeCombo); + if (pageSize == QPrinter::Custom) + printer->setPaperSize(m_customPageSizeControl->pageSize(), QPrinter::Millimeter); + else + printer->setPageSize(pageSize); + printer->setOrientation(comboBoxValue<QPrinter::Orientation>(m_orientationCombo)); + printer->setFullPage(m_fullPageCheckBox->isChecked()); +} + +void PrintDialogPanel::retrieveSettings(const QPrinter *printer) +{ + setComboBoxValue(m_pageSizeCombo, printer->pageSize()); + setComboBoxValue(m_orientationCombo, printer->orientation()); + m_fullPageCheckBox->setChecked(printer->fullPage()); + m_customPageSizeControl->setPageSize(m_printer->paperSize(QPrinter::Millimeter)); +} + +void PrintDialogPanel::enableCustomSizeControl() +{ + m_customPageSizeControl->setEnabled(m_pageSizeCombo->currentIndex() == QPrinter::Custom); +} + +void PrintDialogPanel::showPrintDialog() +{ + applySettings(m_printer.data()); + QPrintDialog dialog(m_printer.data(), this); + dialog.setOptions(m_printDialogOptionsControl->value<QPrintDialog::PrintDialogOptions>()); + dialog.setPrintRange(comboBoxValue<QPrintDialog::PrintRange>(m_printDialogRangeCombo)); + if (dialog.exec() == QDialog::Accepted) + retrieveSettings(m_printer.data()); +} + +void PrintDialogPanel::showPreviewDialog() +{ + applySettings(m_printer.data()); + PrintPreviewDialog dialog(m_printer.data(), this); + dialog.resize(QApplication::desktop()->availableGeometry().size() * 4/ 5); + if (dialog.exec() == QDialog::Accepted) + retrieveSettings(m_printer.data()); +} + +#include "printdialogpanel.moc" + +#endif // !QT_NO_PRINTER diff --git a/tests/manual/dialogs/printdialogpanel.h b/tests/manual/dialogs/printdialogpanel.h new file mode 100644 index 0000000000..4999504a3c --- /dev/null +++ b/tests/manual/dialogs/printdialogpanel.h @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PRINTDIALOGPANEL_H +#define PRINTDIALOGPANEL_H + +#ifndef QT_NO_PRINTER + +#include <QWidget> + +QT_BEGIN_NAMESPACE +class QPrinter; +class QComboBox; +class QGroupBox; +class QPushButton; +class QCheckBox; +QT_END_NAMESPACE + +class PageSizeControl; +class OptionsControl; + +class PrintDialogPanel : public QWidget +{ + Q_OBJECT +public: + explicit PrintDialogPanel(QWidget *parent = 0); + ~PrintDialogPanel(); + +private slots: + void createPrinter(); + void deletePrinter(); + void showPrintDialog(); + void showPreviewDialog(); + void enableCustomSizeControl(); + +private: + void applySettings(QPrinter *printer) const; + void retrieveSettings(const QPrinter *printer); + void enablePanels(); + + QGroupBox *m_creationGroupBox; + QPushButton *m_createButton; + QPushButton *m_deleteButton; + QGroupBox *m_settingsGroupBox; + QCheckBox *m_fullPageCheckBox; + QGroupBox *m_dialogsGroupBox; + OptionsControl *m_printDialogOptionsControl; + QComboBox *m_printDialogRangeCombo; + QComboBox *m_modeCombo; + QComboBox *m_orientationCombo; + QComboBox *m_pageSizeCombo; + PageSizeControl *m_customPageSizeControl; + QScopedPointer<QPrinter> m_printer; +}; + +#endif // !QT_NO_PRINTER +#endif // PRINTDIALOGPANEL_H diff --git a/tests/manual/dialogs/utils.cpp b/tests/manual/dialogs/utils.cpp new file mode 100644 index 0000000000..7e0067c7f3 --- /dev/null +++ b/tests/manual/dialogs/utils.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "utils.h" + +#include <QCheckBox> +#include <QVBoxLayout> + +QComboBox *createCombo(QWidget *parent, const FlagData *d, size_t size) +{ + QComboBox *c = new QComboBox(parent); + for (size_t i = 0; i < size; ++i) + c->addItem(QLatin1String(d[i].description), QVariant(d[i].value)); + return c; +} + +void setComboBoxValue(QComboBox *c, int v) +{ + c->setCurrentIndex(c->findData(QVariant(v))); +} + +OptionsControl::OptionsControl(const QString &title, const FlagData *data, size_t count, QWidget *parent) + : QGroupBox(title, parent) +{ + QVBoxLayout *layout = new QVBoxLayout(this); + for (size_t i = 0; i < count; ++i) { + QCheckBox *box = new QCheckBox(QString::fromLatin1(data[i].description)); + m_checkBoxes.push_back(CheckBoxFlagPair(box, data[i].value)); + layout->addWidget(box); + } +} + +void OptionsControl::setValue(int flags) +{ + foreach (const CheckBoxFlagPair &cf, m_checkBoxes) + cf.first->setChecked(cf.second & flags); +} + +int OptionsControl::intValue() const +{ + int result = 0; + foreach (const CheckBoxFlagPair &cf, m_checkBoxes) { + if (cf.first->isChecked()) + result |= cf.second; + } + return result; +} diff --git a/tests/manual/dialogs/utils.h b/tests/manual/dialogs/utils.h new file mode 100644 index 0000000000..634795627f --- /dev/null +++ b/tests/manual/dialogs/utils.h @@ -0,0 +1,88 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef UTILS_H +#define UTILS_H + +#include <QComboBox> +#include <QGroupBox> +#include <QVariant> +#include <QPair> +#include <QList> + +QT_FORWARD_DECLARE_CLASS(QCheckBox) + +// Associate enum/flag value with a description. +struct FlagData +{ + const char *description; + int value; +}; + +// Helpers for creating combo boxes representing enumeration values from flag data. +QComboBox *createCombo(QWidget *parent, const FlagData *d, size_t size); + +template <class Enum> +Enum comboBoxValue(const QComboBox *c) +{ + return static_cast<Enum>(c->itemData(c->currentIndex()).toInt()); +} + +void setComboBoxValue(QComboBox *c, int v); + +// A group box with check boxes for option flags. +class OptionsControl : public QGroupBox { +public: + explicit OptionsControl(const QString &title, const FlagData *data, size_t count, QWidget *parent); + + void setValue(int flags); + template <class Enum> + Enum value() const { return static_cast<Enum>(intValue()); } + +private: + typedef QPair<QCheckBox *, int> CheckBoxFlagPair; + + int intValue() const; + + QList<CheckBoxFlagPair> m_checkBoxes; +}; + +#endif // UTILS_H diff --git a/tests/manual/widgets/itemviews/autoResizePrecision/tablehorz/testtable1.cpp b/tests/manual/widgets/itemviews/autoResizePrecision/tablehorz/testtable1.cpp index 463366433c..f4ecae83fe 100644 --- a/tests/manual/widgets/itemviews/autoResizePrecision/tablehorz/testtable1.cpp +++ b/tests/manual/widgets/itemviews/autoResizePrecision/tablehorz/testtable1.cpp @@ -100,7 +100,8 @@ protected: void TableDialog::slotValueChanged(int newval) { - tableView->horizontalHeader()->setResizeContentsPrecision(newval, true); + tableView->horizontalHeader()->setResizeContentsPrecision(newval); + tableView->resizeColumnsToContents(); } diff --git a/tests/manual/widgets/itemviews/autoResizePrecision/tablevert/testtable2.cpp b/tests/manual/widgets/itemviews/autoResizePrecision/tablevert/testtable2.cpp index 027801d528..b64a4325f9 100644 --- a/tests/manual/widgets/itemviews/autoResizePrecision/tablevert/testtable2.cpp +++ b/tests/manual/widgets/itemviews/autoResizePrecision/tablevert/testtable2.cpp @@ -110,7 +110,8 @@ protected: void TableDialog::slotValueChanged(int newval) { - tableView->verticalHeader()->setResizeContentsPrecision(newval, true); + tableView->verticalHeader()->setResizeContentsPrecision(newval); + tableView->resizeRowsToContents(); } diff --git a/tests/manual/widgets/itemviews/autoResizePrecision/treeview/testtree.cpp b/tests/manual/widgets/itemviews/autoResizePrecision/treeview/testtree.cpp index c48d933fcd..d9984ca8ea 100644 --- a/tests/manual/widgets/itemviews/autoResizePrecision/treeview/testtree.cpp +++ b/tests/manual/widgets/itemviews/autoResizePrecision/treeview/testtree.cpp @@ -118,7 +118,9 @@ protected: void TreeDialog::slotValueChanged(int newval) { - treeWidget->header()->setResizeContentsPrecision(newval, true); + treeWidget->header()->setResizeContentsPrecision(newval); + for (int u = 0; u < treeWidget->header()->count(); ++u) + treeWidget->resizeColumnToContents(u); } int main(int argc, char *argv[]) |