Merge remote-tracking branch 'origin/5.6' into dev

Conflicts:
	src/corelib/io/io.pri
	src/corelib/io/qdatastream.cpp
	src/corelib/io/qdatastream.h
	src/network/socket/qabstractsocket.cpp
	src/plugins/platforminputcontexts/ibus/qibusplatforminputcontext.cpp
	src/plugins/platforms/cocoa/qcocoaaccessibilityelement.h
	src/widgets/styles/qgtkstyle.cpp
	tests/auto/corelib/mimetypes/qmimedatabase/qmimedatabase-cache/qmimedatabase-cache.pro
	tests/auto/corelib/mimetypes/qmimedatabase/qmimedatabase-xml/qmimedatabase-xml.pro
	tests/auto/dbus/qdbusconnection/qdbusconnection.pro
	tests/auto/dbus/qdbuspendingcall/tst_qdbuspendingcall.cpp
	tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp

Change-Id: I347549a024eb5bfa986699e0a11f96cc55c797a7
This commit is contained in:
Liang Qi 2015-09-25 14:02:04 +02:00
commit a1ad9a74eb
547 changed files with 10478 additions and 8011 deletions

View File

@ -6,7 +6,7 @@
You may use, distribute and copy the Qt GUI Toolkit under the terms of
GNU Lesser General Public License version 3. That license references
the General Public License version 3, that is displayed below. Other
portions of the Qt Toolkit may be licensed directly other this license.
portions of the Qt Toolkit may be licensed directly under this license.
-------------------------------------------------------------------------

View File

@ -4,8 +4,8 @@
Contact: http://www.qt.io/licensing/
You may use, distribute and copy the Qt GUI Toolkit under the terms of
GNU Lesser General Public License version 3, which is displayed
below. This license makes reference to the version 3 of the GNU General
GNU Lesser General Public License version 3, which is displayed below.
This license makes reference to the version 3 of the GNU General
Public License, which you can find in the LICENSE.GPLv3 file.
-------------------------------------------------------------------------

View File

@ -1,9 +1,9 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
** This file is part of the FOO module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@ -31,36 +31,24 @@
**
****************************************************************************/
#ifndef QKMSCURSOR_H
#define QKMSCURSOR_H
#include <atomic>
#include <cstdint>
#include <qpa/qplatformcursor.h>
struct gbm_device;
struct gbm_bo;
QT_BEGIN_NAMESPACE
class QKmsScreen;
class QKmsCursor : public QPlatformCursor
void test(volatile std::atomic<std::int64_t> &a)
{
public:
QKmsCursor(QKmsScreen *screen);
~QKmsCursor();
std::int64_t v = a.load(std::memory_order_acquire);
while (!a.compare_exchange_strong(v, v + 1,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
v = a.exchange(v - 1);
}
void pointerEvent(const QMouseEvent &event) Q_DECL_OVERRIDE;
void changeCursor(QCursor *windowCursor, QWindow *window) Q_DECL_OVERRIDE;
a.store(v + 1, std::memory_order_release);
}
private:
QKmsScreen *m_screen;
gbm_device *m_graphicsBufferManager;
gbm_bo *m_cursorBufferObject;
QPlatformCursorImage *m_cursorImage;
bool m_moved;
QSize m_cursorSize;
};
QT_END_NAMESPACE
#endif // QKMSCURSOR_H
int main(int, char **)
{
void *ptr = (void*)0xffffffc0; // any random pointer
test(*reinterpret_cast<std::atomic<std::int64_t> *>(ptr));
return 0;
}

View File

@ -0,0 +1,3 @@
SOURCES = atomic64.cpp
CONFIG += c++11 console
CONFIG -= qt

View File

@ -1,9 +1,9 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
** This file is part of the configuration module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@ -31,41 +31,10 @@
**
****************************************************************************/
#ifndef QKMSCONTEXT_H
#define QKMSCONTEXT_H
#if __cplusplus > 201103L
// Compiler claims to support C++14, trust it
#else
# error "__cplusplus must be > 201103L (the value of C++11)"
#endif
#include <qpa/qplatformopenglcontext.h>
#define EGL_EGLEXT_PROTOTYPES 1
#include <EGL/egl.h>
QT_BEGIN_NAMESPACE
class QKmsDevice;
class QKmsContext : public QPlatformOpenGLContext
{
public:
QKmsContext(QOpenGLContext *context, QKmsDevice *device);
bool makeCurrent(QPlatformSurface *surface) Q_DECL_OVERRIDE;
void doneCurrent() Q_DECL_OVERRIDE;
void swapBuffers(QPlatformSurface *surface) Q_DECL_OVERRIDE;
void (*getProcAddress(const QByteArray &procName)) () Q_DECL_OVERRIDE;
bool isValid() const Q_DECL_OVERRIDE;
QSurfaceFormat format() const Q_DECL_OVERRIDE;
EGLContext eglContext() const;
private:
EGLContext m_eglContext;
QSurfaceFormat m_format;
QKmsDevice *m_device;
};
QT_END_NAMESPACE
#endif // QKMSCONTEXT_H
int main(int, char **) { return 0; }

View File

@ -0,0 +1,3 @@
SOURCES = c++14.cpp
CONFIG += c++11 c++14 console
CONFIG -= qt

View File

@ -0,0 +1,40 @@
/****************************************************************************
**
** Copyright (C) 2015 Intel Corporation.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the configuration module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#if __cplusplus > 201402L
// Compiler claims to support experimental C++1z, trust it
#else
# error "__cplusplus must be > 201402L (the value for C++14)"
#endif
int main(int, char **) { return 0; }

View File

@ -0,0 +1,3 @@
SOURCES = c++1z.cpp
CONFIG += c++11 c++14 c++1z console
CONFIG -= qt

View File

@ -0,0 +1 @@
__cplusplus

View File

@ -0,0 +1,14 @@
TEMPLATE = aux
CONFIG -= qt c++11
PREPROCESSOR_SOURCES += c++default.cpp
preprocessor.commands = $(CXX) $(CXXFLAGS) $(INCPATH) -o $@ -E $<
msvc:preprocessor.commands = $(CXX) $(CXXFLAGS) $(INCPATH) -E ${QMAKE_FILE_IN} > ${QMAKE_FILE_OUT}
preprocessor.output = ${QMAKE_FILE_BASE}.ii
preprocessor.input = PREPROCESSOR_SOURCES
preprocessor.variable_out = GENERATED_FILES
QMAKE_EXTRA_COMPILERS += preprocessor
all.target = all
all.depends += c++default.ii
QMAKE_EXTRA_TARGETS += all

View File

@ -5,12 +5,15 @@ VERBOSE=$2
SRCDIR=$3
OUTDIR=$4
LFLAGS=$SYSROOT_FLAG
CXXFLAGS=$SYSROOT_FLAG
# debuggery
[ "$VERBOSE" = "yes" ] && echo "Testing size of pointers ... ($*)"
# build and run a test program
test -d "$OUTDIR/config.tests/unix/ptrsize" || mkdir -p "$OUTDIR/config.tests/unix/ptrsize"
"$OUTDIR/bin/qmake" -nocache -spec "$QMKSPEC" "CONFIG-=app_bundle" "$SRCDIR/config.tests/unix/ptrsize/ptrsizetest.pro" -o "$OUTDIR/config.tests/unix/ptrsize/Makefile" >/dev/null 2>&1
"$OUTDIR/bin/qmake" -nocache -spec "$QMKSPEC" "CONFIG-=app_bundle" "QMAKE_LFLAGS*=$LFLAGS" "QMAKE_CXXFLAGS*=$CXXFLAGS" "$SRCDIR/config.tests/unix/ptrsize/ptrsizetest.pro" -o "$OUTDIR/config.tests/unix/ptrsize/Makefile" >/dev/null 2>&1
cd "$OUTDIR/config.tests/unix/ptrsize"
if [ "$VERBOSE" = "yes" ]; then

167
configure vendored
View File

@ -2,7 +2,7 @@
#############################################################################
##
## Copyright (C) 2015 The Qt Company Ltd.
## Copyright (C) 2013 Intel Corporation.
## Copyright (C) 2015 Intel Corporation.
## Contact: http://www.qt.io/licensing/
##
## This file is the build configuration utility of the Qt Toolkit.
@ -662,6 +662,7 @@ CFG_SYSTEM_PROXIES=no
CFG_ANDROID_STYLE_ASSETS=yes
CFG_GSTREAMER=auto
CFG_GSTREAMER_VERSION=""
CFG_ATOMIC64=auto
# Target architecture
CFG_ARCH=
@ -769,7 +770,7 @@ CFG_SANITIZE_MEMORY=no
CFG_SANITIZE_UNDEFINED=no
CFG_PCRE=auto
QPA_PLATFORM_GUARD=yes
CFG_CXX11=auto
CFG_STDCXX=auto
CFG_DIRECTWRITE=no
CFG_WERROR=auto
CFG_HEADERSCLEAN=auto
@ -935,6 +936,7 @@ while [ "$#" -gt 0 ]; do
-sdk| \
-arch| \
-host-arch| \
-c++std | \
-mysql_config| \
-psql_config| \
-qpa| \
@ -1403,18 +1405,6 @@ while [ "$#" -gt 0 ]; do
unixware7-g++)
PLATFORM=unixware-g++
;;
macx-g++-64)
PLATFORM=macx-g++
NATIVE_64_ARCH=
case `uname -p` in
i386) NATIVE_64_ARCH="x86_64" ;;
powerpc) NATIVE_64_ARCH="ppc64" ;;
*) echo "WARNING: Can't detect CPU architecture for macx-g++-64" ;;
esac
if [ ! -z "$NATIVE_64_ARCH" ]; then
QTCONFIG_CONFIG="$QTCONFIG_CONFIG $NATIVE_64_ARCH"
fi
;;
esac
;;
xplatform)
@ -2234,12 +2224,31 @@ while [ "$#" -gt 0 ]; do
fi
;;
c++11)
if [ "$VAL" = "yes" ] || [ "$VAL" = "no" ]; then
CFG_CXX11="$VAL"
if [ "$VAL" = "yes" ]; then
CFG_STDCXX="c++11"
elif [ "$VAL" = "no" ]; then
CFG_STDCXX="c++98"
else
UNKNOWN_OPT=yes
fi
;;
c++std)
case "$VAL" in
c++98|c++11|c++14|c++1z|auto)
CFG_STDCXX="$VAL"
;;
98|11|14|1z)
CFG_STDCXX="c++$VAL"
;;
1y|c++1y)
CFG_STDCXX="c++14"
;;
*)
echo >&2 "Invalid C++ edition: $VAL; valid options are: c++98 c++11 c++14 c++1z auto"
ERROR=yes
;;
esac
;;
system-proxies)
if [ "$VAL" = "yes" ] || [ "$VAL" = "no" ]; then
CFG_SYSTEM_PROXIES="$VAL"
@ -2411,8 +2420,8 @@ Configure options:
-confirm-license ... Automatically acknowledge the license (use with
either -opensource or -commercial)
-no-c++11 .......... Do not compile Qt with C++11 support enabled.
+ -c++11 ............. Compile Qt with C++11 support enabled.
-c++std <edition> .. Compile Qt with C++ standard edition (c++98, c++11, c++14, c++1z)
Default: highest supported
* -shared ............ Create and use shared Qt libraries.
-static ............ Create and use static Qt libraries.
@ -2649,15 +2658,15 @@ Additional options:
-no-eglfs .......... Do not compile EGLFS (EGL Full Screen/Single Surface) support.
* -eglfs ............. Compile EGLFS support.
-no-kms ............ Do not compile EGLFS KMS backend.
* -kms ............... Compile EGLFS KMS backend.
-no-directfb ....... Do not compile DirectFB support.
* -directfb .......... Compile DirectFB support.
-no-linuxfb ........ Do not compile Linux Framebuffer support.
* -linuxfb ........... Compile Linux Framebuffer support.
-no-kms ............ Do not compile KMS support.
* -kms ............... Compile KMS support (Requires EGL).
* -no-mirclient....... Do not compile Mir client support.
-mirclient.......... Compile Mir client support.
@ -2690,7 +2699,7 @@ Additional options:
-no-gstreamer ....... Do not support GStreamer.
+ -gstreamer <version> Enable GStreamer support
With no parameter, this will attempt to auto-detect GStreamer 0.10 and
1.0. GStreamer 0.10 is used by default when available.
1.0. GStreamer 1.0 is used by default when available.
Use 0.10 or 1.0 for <version> to override auto-detection.
* -no-system-proxies .. Do not use system network proxies by default.
@ -2725,7 +2734,7 @@ MacOS/iOS options:
* -securetransport ... Use SecureTransport instead of OpenSSL
-no-securetransport Do not use SecureTransport, either use OpenSSL or dot not use any SSL backend
-no-securetransport Do not use SecureTransport, either use OpenSSL or do not use any SSL backend
at all (if combined with -no-openssl).
-sdk <sdk> ......... Build Qt using Apple provided SDK <sdk>. The argument should be
@ -3179,13 +3188,13 @@ if [ "$XPLATFORM_ANDROID" = "yes" ]; then
;;
macx-*)
CFG_DEFAULT_ANDROID_NDK_HOST=darwin-x86
if [ ! -z "$NATIVE_64_ARCH" ] && [ -d "$CFG_DEFAULT_ANDROID_NDK_ROOT/toolchains/arm-linux-androideabi-$CFG_DEFAULT_ANDROID_NDK_TOOLCHAIN_VERSION/prebuilt/darwin-x86_64" ]; then
if [ -d "$CFG_DEFAULT_ANDROID_NDK_ROOT/toolchains/arm-linux-androideabi-$CFG_DEFAULT_ANDROID_NDK_TOOLCHAIN_VERSION/prebuilt/darwin-x86_64" ]; then
CFG_DEFAULT_ANDROID_NDK_HOST=darwin-x86_64
fi
;;
win32-*)
CFG_DEFAULT_ANDROID_NDK_HOST=windows
if [ ! -z "$NATIVE_64_ARCH" ] && [ -d "$CFG_DEFAULT_ANDROID_NDK_ROOT/toolchains/arm-linux-androideabi-$CFG_DEFAULT_ANDROID_NDK_TOOLCHAIN_VERSION/prebuilt/windows-x86_64" ]; then
if [ -d "$CFG_DEFAULT_ANDROID_NDK_ROOT/toolchains/arm-linux-androideabi-$CFG_DEFAULT_ANDROID_NDK_TOOLCHAIN_VERSION/prebuilt/windows-x86_64" ]; then
CFG_DEFAULT_ANDROID_NDK_HOST=windows-x86_64
fi
;;
@ -4323,24 +4332,71 @@ if [ "$CFG_SEPARATE_DEBUG_INFO" = "yes" ]; then
fi
fi
# Detect C++11 support
if [ "$CFG_CXX11" != "no" ]; then
# Configure detects compiler features based on cross compiler, so we need
# to explicitly disable C++11 on Mac to avoid breaking builds where the
# host compiler does not support it.
if [ "$BUILD_ON_MAC" = "yes" ] && [ "$XPLATFORM_ANDROID" = "yes" ]; then
CFG_CXX11="no"
elif compileTest common/c++11 "C++11"; then
CFG_CXX11="yes"
elif [ "$CFG_CXX11" != "auto" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo "C++11 support cannot be enabled due to functionality tests!"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
exit 101
# Detect C++11 & up support
# Configure detects compiler features based on cross compiler, so we need
# to explicitly disable C++11 on Mac to avoid breaking builds where the
# host compiler does not support it.
stdcxx_error=false
if [ "$BUILD_ON_MAC" = "yes" ] && [ "$XPLATFORM_ANDROID" = "yes" ]; then
CFG_STDCXX="c++98"
elif [ "$CFG_STDCXX" = "c++98" ]; then
: # CFG_STDCXX is correct
elif ! compileTest common/c++11 "C++11"; then
if [ "$CFG_STDCXX" != "auto" ]; then
stdcxx_error=true
else
CFG_CXX11="no"
CFG_STDCXX="c++98"
fi
elif [ "$CFG_STDCXX" = "c++11" ]; then
: # CFG_STDCXX is correct
elif ! compileTest common/c++14 "C++14"; then
if [ "$CFG_STDCXX" != "auto" ]; then
stdcxx_error=true
else
CFG_STDCXX="c++11"
fi
elif [ "$CFG_STDCXX" = "c++14" ]; then
: # CFG_STDCXX is correct
elif ! compileTest common/c++1z "C++1z"; then
if [ "$CFG_STDCXX" != "auto" ]; then
stdcxx_error=true
else
CFG_STDCXX="c++14"
fi
else
CFG_STDCXX="c++1z"
fi
if $stdcxx_error && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
echo "$CFG_STDCXX support cannot be enabled due to functionality tests!"
echo " Turn on verbose messaging (-v) to $0 to see the final report."
echo " If you believe this message is in error you may use the continue"
echo " switch (-continue) to $0 to continue."
exit 101
fi
# Detect which edition of the C++ standard the compiler defaults to
CFG_STDCXX_DEFAULT=199711
if compileTest common/c++default "default C++ standard edition"; then
if [ -e "$outpath/config.tests/common/c++default/c++default.ii" ]; then
CFG_STDCXX_DEFAULT=`sed -n '/^[0-9]/s/L//p' "$outpath/config.tests/common/c++default/c++default.ii"`
else
if [ "$OPT_VERBOSE" = "yes" ]; then
echo "Failed to run the preprocessor, something is wrong with your compiler"
fi
if [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then
exit 101
fi
fi
fi
# Detect whether 64-bit std::atomic works -- some 32-bit platforms require extra library support
if compileTest common/atomic64 "64-bit std::atomic"; then
CFG_ATOMIC64=yes
elif compileTest common/atomic64 "64-bit std::atomic in -latomic" -latomic; then
CFG_ATOMIC64=libatomic
else
CFG_ATOMIC64=no
fi
# detect sse2 support
@ -6026,12 +6082,12 @@ fi
# detect GStreamer support
if [ "$CFG_GSTREAMER" = "auto" ] || [ "$CFG_GSTREAMER" = "yes" ]; then
if compileTest unix/gstreamer "GStreamer 0.10" -config gst-0.10; then
CFG_GSTREAMER=yes
CFG_GSTREAMER_VERSION=0.10
elif compileTest unix/gstreamer "GStreamer 1.0" -config gst-1.0; then
if compileTest unix/gstreamer "GStreamer 1.0" -config gst-1.0; then
CFG_GSTREAMER=yes
CFG_GSTREAMER_VERSION=1.0
elif compileTest unix/gstreamer "GStreamer 0.10" -config gst-0.10; then
CFG_GSTREAMER=yes
CFG_GSTREAMER_VERSION=0.10
else
if [ "$CFG_GSTREAMER" = "yes" ]; then
echo "GStreamer support cannot be enabled due to functionality tests!"
@ -6069,7 +6125,19 @@ fi
# ask for all that hasn't been auto-detected or specified in the arguments
#-------------------------------------------------------------------------------
[ "$CFG_CXX11" = "yes" ] && QT_CONFIG="$QT_CONFIG c++11"
if [ "$CFG_STDCXX" != "c++98" ]; then
QT_CONFIG="$QT_CONFIG c++11"
if [ "$CFG_STDCXX" != "c++11" ]; then
QT_CONFIG="$QT_CONFIG c++14"
if [ "$CFG_STDCXX" != "c++14" ]; then
QT_CONFIG="$QT_CONFIG c++1z"
fi
fi
fi
if [ "$CFG_ATOMIC64" = "libatomic" ]; then
QMAKE_CONFIG="$QMAKE_CONFIG atomic64-libatomic"
fi
if [ "$CFG_SILENT" = "yes" ]; then
QMAKE_CONFIG="$QMAKE_CONFIG silent"
@ -6625,6 +6693,10 @@ else
echo "#define QT_POINTER_SIZE $?" >>"$outpath/src/corelib/global/qconfig.h.new"
fi
if [ "$CFG_ATOMIC64" = "no" ]; then
echo "#define QT_NO_STD_ATOMIC64" >> "$outpath/src/corelib/global/qconfig.h.new"
fi
#REDUCE_RELOCATIONS is a elf/unix only thing, so not in windows configure.exe
if [ "$CFG_REDUCE_RELOCATIONS" = "yes" ]; then
echo "#define QT_REDUCE_RELOCATIONS" >>"$outpath/src/corelib/global/qconfig.h.new"
@ -6891,6 +6963,7 @@ fi
if [ -n "$RPATH_FLAGS" ]; then
echo "QMAKE_RPATHDIR += $RPATH_FLAGS" >> "$QTCONFIG.tmp"
fi
echo "QT_COMPILER_STDCXX = $CFG_STDCXX_DEFAULT" >> "$QTCONFIG.tmp"
if [ -n "$QT_GCC_MAJOR_VERSION" ]; then
echo "QT_GCC_MAJOR_VERSION = $QT_GCC_MAJOR_VERSION" >> "$QTCONFIG.tmp"
echo "QT_GCC_MINOR_VERSION = $QT_GCC_MINOR_VERSION" >> "$QTCONFIG.tmp"
@ -7085,7 +7158,7 @@ else
fi
unset build_mode release
echo " Using sanitizer(s)...... $CFG_SANITIZERS"
echo " Using C++11 ............ $CFG_CXX11"
echo " Using C++ standard ..... $CFG_STDCXX"
echo " Using gold linker....... $CFG_USE_GOLD_LINKER"
echo " Using new DTAGS ........ $CFG_ENABLE_NEW_DTAGS"
echo " Using PCH .............. $CFG_PRECOMPILE"

View File

@ -476,7 +476,7 @@
\title Qt Creator: Adding Debuggers
*/
/*!
\externalpage http://doc.qt.io/qtcreator/creator-mobile-app-tutorial.html
\externalpage http://doc.qt.io/qtcreator/qtcreator-accelbubble-example.html
\title Qt Creator: Creating a Mobile Application
*/
/*!

View File

@ -3,6 +3,7 @@
HTML.stylesheets = template/style/online.css \
template/style/gsc.css \
template/style/list_arrow.png \
template/style/list_expand.png \
template/style/icomoon.eot \
template/style/icomoon.svg \
template/style/icomoon.ttf \
@ -15,6 +16,7 @@ HTML.stylesheets = template/style/online.css \
qhp.extraFiles += style/online.css \
style/gsc.css \
style/list_arrow.png \
style/list_expand.png \
style/icomoon.eot \
style/icomoon.svg \
style/icomoon.ttf \

View File

@ -1,8 +1,25 @@
var vOffset = 65;
var vOffset_init = 65;
var vOffset = vOffset_init;
var c = 'collapsed';
function toggleList(toggle, content, maxItems) {
if (toggle.css('display') == 'none') {
vOffset = vOffset_init;
toggle.removeClass(c);
content.show();
return;
} else
vOffset = 8;
if (maxItems > content.children().length)
return;
content.hide();
toggle.addClass(c);
}
$(function () {
$('a[href*=#]:not([href=#])').on('click', function (e) {
if (e.which == 2)
if (e.which == 2 || e.metaKey || e.ctrlKey || e.shiftKey)
return true;
var target = $(this.hash.replace(/(\.)/g, "\\$1"));
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
@ -14,11 +31,50 @@ $(function () {
});
$(window).load(function () {
var h = window.location.hash;
var re = /[^a-z0-9_\.\#\-]/i
if (h.length > 1 && !re.test(h)) {
setTimeout(function () {
$(window).scrollTop($(h.replace(/(\.)/g, "\\$1")).offset().top - vOffset);
}, 0);
var hashChanged = function() {
var h = window.location.hash;
var re = /[^a-z0-9_\.\#\-]/i
if (h.length > 1 && !re.test(h)) {
setTimeout(function () {
var tgt = $(h.replace(/(\.)/g, "\\$1"));
tgt = tgt.length ? tgt : $('[name=' + h.slice(1) + ']');
$(window).scrollTop(tgt.offset().top - vOffset);
}, 0);
}
}
$(window).bind('hashchange', hashChanged);
hashChanged.call();
if (!$('.sidebar toc').is(':empty')) {
$('<div id="toc-toggle"></div>').prependTo('.sidebar .toc');
var toc = $('.sidebar .toc ul');
var tocToggle = $('#toc-toggle');
var tocCallback = function() { toggleList(tocToggle, toc, 4); };
$('#toc-toggle').on('click', function(e) {
e.stopPropagation();
toc.toggle();
tocToggle.toggleClass(c);
});
tocCallback.call();
$(window).resize(tocCallback);
}
if (!$('#sidebar-content').is(':empty')) {
$('#sidebar-content h2').first().clone().prependTo('#sidebar-content');
$('<div id="sidebar-toggle"></div>').prependTo('#sidebar-content');
var sb = $('#sidebar-content .sectionlist');
var sbToggle = $('#sidebar-toggle');
var sbCallback = function() { toggleList(sbToggle, sb, 0); };
$('#sidebar-toggle').on('click', function(e) {
e.stopPropagation();
sb.toggle();
sbToggle.toggleClass(c);
});
sbCallback.call();
$(window).resize(sbCallback);
}
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 710 B

View File

@ -525,6 +525,21 @@ body.qt-account #navbar .navbar-oneQt h2 {
position:absolute;
transition:none;
}
#sidebar-toggle,#toc-toggle {
width:24px;
height:14px;
background-size:24px 28px;
cursor:pointer;
background-image:url("list_expand.png");
float:right
}
#sidebar-toggle.collapsed,
#toc-toggle.collapsed {
background-position:bottom left
}
#sidebar-content > h2 {
display:none
}
.cookies_yum .close:hover {
background-position:bottom left
}
@ -1128,7 +1143,7 @@ dd {
.mainContent b {
font-weight:600
}
.context ul {
.context ul,.context ol {
margin-bottom:1.5em
}
.mainContent ul ul {
@ -1282,6 +1297,9 @@ div.main_index .row:after {
div.table {
overflow-x:auto
}
.context tr > td > pre {
font-size:0.85em
}
p.qt_commercial {
border:3px solid #5caa15;
margin:0 auto;
@ -1312,7 +1330,6 @@ pre {
line-height:1.5;
overflow-x:auto;
margin-bottom:25px;
overflow-x:auto;
padding:25px;
margin-top:0.75em
}
@ -1376,6 +1393,9 @@ pre:hover>.copy_text {
margin:0;
border:none
}
#sidebar-toggle,#toc-toggle {
display:none
}
@media (max-width: 980px) {
body {
font-size:calc-em(14px)
@ -1413,7 +1433,8 @@ pre:hover>.copy_text {
visibility:hidden
}
.col-2 h2,.toc h3,.sidebar-content h2,.sidebar-content h3,.sectionlist h2 {
text-align:center
text-align:center;
margin-bottom:0
}
div.main_index .row:after {
content:none
@ -1438,6 +1459,12 @@ pre:hover>.copy_text {
margin-bottom:1em;
padding:20px
}
#sidebar-toggle,#toc-toggle {
display:block
}
#sidebar-toggle.collapsed + h2 {
display:block
}
.mainContent p {
line-height:1.56em;
margin-bottom:1em;
@ -1446,6 +1473,9 @@ pre:hover>.copy_text {
table td,table th {
padding:5px 5px
}
.sectionlist {
padding:0
}
}
[id]:target,[name]:target,[name]:target+* {
-webkit-animation:highlighter 3s;
@ -1453,22 +1483,22 @@ pre:hover>.copy_text {
}
@-webkit-keyframes highlighter {
25% {
background-color:#46a2da;
color:#fff
background-color:#d1e8f6;
color:#444
}
75% {
background-color:#46a2da;
color:#fff
background-color:#d1e8f6;
color:#444
}
}
@keyframes highlighter {
25% {
background-color:#46a2da;
color:#fff
background-color:#d1e8f6;
color:#444
}
75% {
background-color:#46a2da;
color:#fff
background-color:#d1e8f6;
color:#444
}
}
@-webkit-keyframes copypaste {
@ -1580,7 +1610,7 @@ img.gsc-branding-img {
input.gsc-search-button {
background-color: white !important;
height: 35px !important;
width: 35px !important;
width: 25px !important;
color: transparent !important;
background-image: url("doc_search.png") !important;
background-size: 25px auto;

View File

@ -66,8 +66,8 @@ Window::Window()
setLayout(layout);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), native, SLOT(animate()));
connect(timer, SIGNAL(timeout()), openGL, SLOT(animate()));
connect(timer, &QTimer::timeout, native, &Widget::animate);
connect(timer, &QTimer::timeout, openGL, &GLWidget::animate);
timer->start(50);
}
//! [0]

View File

@ -221,5 +221,5 @@ void RenderWindow::render()
// only here to make the UI widgets more responsive on slower machines. We
// can afford it since our rendering is so lightweight.
const int interval = 5;
QTimer::singleShot(interval, this, SLOT(render()));
QTimer::singleShot(interval, this, &RenderWindow::render);
}

View File

@ -55,8 +55,11 @@ GLWidget::GLWidget(QWidget *parent)
// --transparent causes the clear color to be transparent. Therefore, on systems that
// support it, the widget will become transparent apart from the logo.
m_transparent = QCoreApplication::arguments().contains(QStringLiteral("--transparent"));
if (m_transparent)
setAttribute(Qt::WA_TranslucentBackground);
if (m_transparent) {
QSurfaceFormat fmt = format();
fmt.setAlphaBufferSize(8);
setFormat(fmt);
}
}
GLWidget::~GLWidget()

View File

@ -59,6 +59,10 @@ int main(int argc, char *argv[])
QSurfaceFormat::setDefaultFormat(fmt);
MainWindow mainWindow;
if (QCoreApplication::arguments().contains(QStringLiteral("--transparent"))) {
mainWindow.setAttribute(Qt::WA_TranslucentBackground);
mainWindow.setAttribute(Qt::WA_NoSystemBackground, false);
}
mainWindow.resize(mainWindow.sizeHint());
int desktopArea = QApplication::desktop()->width() *
QApplication::desktop()->height();

View File

@ -92,7 +92,7 @@ GLWindow::GLWindow()
rAnim->setLoopCount(-1);
rAnim->start();
QTimer::singleShot(4000, this, SLOT(startSecondStage()));
QTimer::singleShot(4000, this, &GLWindow::startSecondStage);
}
GLWindow::~GLWindow()

View File

@ -46,11 +46,15 @@
#include <QVector3D>
#include "../hellogl2/logo.h"
QT_BEGIN_NAMESPACE
class QOpenGLTexture;
class QOpenGLShaderProgram;
class QOpenGLBuffer;
class QOpenGLVertexArrayObject;
QT_END_NAMESPACE
class GLWindow : public QOpenGLWindow
{
Q_OBJECT

View File

@ -119,7 +119,7 @@ void Renderer::setAnimating(HelloWindow *window, bool animating)
if (animating) {
m_windows << window;
if (m_windows.size() == 1)
QTimer::singleShot(0, this, SLOT(render()));
QTimer::singleShot(0, this, &Renderer::render);
} else {
m_currentWindow = 0;
m_windows.removeOne(window);
@ -184,7 +184,7 @@ void Renderer::render()
m_fAngle += 1.0f;
QTimer::singleShot(0, this, SLOT(render()));
QTimer::singleShot(0, this, &Renderer::render);
}
Q_GLOBAL_STATIC(QMutex, initMutex)

View File

@ -121,13 +121,13 @@ int main(int argc, char *argv[])
}
for (int i = 0; i < renderThreads.size(); ++i) {
QObject::connect(qGuiApp, SIGNAL(lastWindowClosed()), renderThreads.at(i), SLOT(quit()));
QObject::connect(qGuiApp, &QGuiApplication::lastWindowClosed, renderThreads.at(i), &QThread::quit);
renderThreads.at(i)->start();
}
// Quit after 10 seconds. For platforms that do not have windows that are closeable.
if (QCoreApplication::arguments().contains(QStringLiteral("--timeout")))
QTimer::singleShot(10000, qGuiApp, SLOT(quit()));
QTimer::singleShot(10000, qGuiApp, &QCoreApplication::quit);
const int exitValue = app.exec();

View File

@ -83,9 +83,11 @@ PaintedWindow::PaintedWindow()
m_targetOrientation = contentOrientation();
m_nextTargetOrientation = Qt::PrimaryOrientation;
connect(screen(), SIGNAL(orientationChanged(Qt::ScreenOrientation)), this, SLOT(orientationChanged(Qt::ScreenOrientation)));
connect(m_animation, SIGNAL(finished()), this, SLOT(rotationDone()));
connect(this, SIGNAL(rotationChanged(qreal)), this, SLOT(paint()));
connect(screen(), &QScreen::orientationChanged, this, &PaintedWindow::orientationChanged);
connect(m_animation, &QAbstractAnimation::finished, this, &PaintedWindow::rotationDone);
typedef void (PaintedWindow::*PaintedWindowVoidSlot)();
connect(this, &PaintedWindow::rotationChanged,
this, static_cast<PaintedWindowVoidSlot>(&PaintedWindow::paint));
}
void PaintedWindow::exposeEvent(QExposeEvent *)

View File

@ -51,6 +51,8 @@
#include "glwidget.h"
typedef void (QWidget::*QWidgetVoidSlot)();
MainWindow::MainWindow()
: m_nextX(1), m_nextY(1)
{
@ -107,34 +109,27 @@ MainWindow::MainWindow()
groupBox->setLayout(m_layout);
QMenu *fileMenu = menuBar()->addMenu("&File");
fileMenu->addAction("E&xit", this, &QWidget::close);
QMenu *showMenu = menuBar()->addMenu("&Show");
QMenu *helpMenu = menuBar()->addMenu("&Help");
QAction *exit = new QAction("E&xit", fileMenu);
QAction *aboutQt = new QAction("About Qt", helpMenu);
QAction *showLogo = new QAction("Show 3D Logo", showMenu);
QAction *showTexture = new QAction("Show 2D Texture", showMenu);
QAction *showBubbles = new QAction("Show bubbles", showMenu);
showMenu->addAction("Show 3D Logo", glwidget, &GLWidget::setLogo);
showMenu->addAction("Show 2D Texture", glwidget, &GLWidget::setTexture);
QAction *showBubbles = showMenu->addAction("Show bubbles", glwidget, &GLWidget::setShowBubbles);
showBubbles->setCheckable(true);
showBubbles->setChecked(true);
fileMenu->addAction(exit);
helpMenu->addAction(aboutQt);
showMenu->addAction(showLogo);
showMenu->addAction(showTexture);
showMenu->addAction(showBubbles);
QMenu *helpMenu = menuBar()->addMenu("&Help");
helpMenu->addAction("About Qt", qApp, &QApplication::aboutQt);
connect(exit, SIGNAL(triggered(bool)), this, SLOT(close()));
connect(aboutQt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt()));
connect(m_timer, &QTimer::timeout,
glwidget, static_cast<QWidgetVoidSlot>(&QWidget::update));
connect(m_timer, SIGNAL(timeout()), glwidget, SLOT(update()));
connect(showLogo, SIGNAL(triggered(bool)), glwidget, SLOT(setLogo()));
connect(showTexture, SIGNAL(triggered(bool)), glwidget, SLOT(setTexture()));
connect(showBubbles, SIGNAL(triggered(bool)), glwidget, SLOT(setShowBubbles(bool)));
connect(slider, SIGNAL(valueChanged(int)), glwidget, SLOT(setScaling(int)));
connect(slider, &QAbstractSlider::valueChanged, glwidget, &GLWidget::setScaling);
connect(transparent, &QCheckBox::toggled, glwidget, &GLWidget::setTransparent);
connect(updateInterval, SIGNAL(valueChanged(int)), this, SLOT(updateIntervalChanged(int)));
typedef void (QSpinBox::*QSpinBoxIntSignal)(int);
connect(updateInterval, static_cast<QSpinBoxIntSignal>(&QSpinBox::valueChanged),
this, &MainWindow::updateIntervalChanged);
connect(timerBased, &QCheckBox::toggled, this, &MainWindow::timerUsageChanged);
connect(timerBased, &QCheckBox::toggled, updateInterval, &QWidget::setEnabled);
@ -157,7 +152,7 @@ void MainWindow::addNew()
return;
GLWidget *w = new GLWidget(this, false, qRgb(qrand() % 256, qrand() % 256, qrand() % 256));
m_glWidgets << w;
connect(m_timer, SIGNAL(timeout()), w, SLOT(update()));
connect(m_timer, &QTimer::timeout, w, static_cast<QWidgetVoidSlot>(&QWidget::update));
m_layout->addWidget(w, m_nextY, m_nextX, 1, 1);
if (m_nextX == 3) {
m_nextX = 1;

View File

@ -163,16 +163,20 @@ void OpenGLWindow::keyPressEvent(QKeyEvent *e)
void OpenGLWindow::setAnimating(bool enabled)
{
typedef void (QPaintDeviceWindow::*QPaintDeviceWindowVoidSlot)();
if (enabled) {
// Animate continuously, throttled by the blocking swapBuffers() call the
// QOpenGLWindow internally executes after each paint. Once that is done
// (frameSwapped signal is emitted), we schedule a new update. This
// obviously assumes that the swap interval (see
// QSurfaceFormat::setSwapInterval()) is non-zero.
connect(this, SIGNAL(frameSwapped()), this, SLOT(update()));
connect(this, &QOpenGLWindow::frameSwapped,
this, static_cast<QPaintDeviceWindowVoidSlot>(&QPaintDeviceWindow::update));
update();
} else {
disconnect(this, SIGNAL(frameSwapped()), this, SLOT(update()));
disconnect(this, &QOpenGLWindow::frameSwapped,
this, static_cast<QPaintDeviceWindowVoidSlot>(&QPaintDeviceWindow::update));
}
}

View File

@ -59,8 +59,8 @@ Window::Window()
glWidgets[i][j]->rotateBy(+42 * 16, +42 * 16, -21 * 16);
mainLayout->addWidget(glWidgets[i][j], i, j);
connect(glWidgets[i][j], SIGNAL(clicked()),
this, SLOT(setCurrentGlWidget()));
connect(glWidgets[i][j], &GLWidget::clicked,
this, &Window::setCurrentGlWidget);
}
}
setLayout(mainLayout);
@ -68,7 +68,7 @@ Window::Window()
currentGlWidget = glWidgets[0][0];
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(rotateOneStep()));
connect(timer, &QTimer::timeout, this, &Window::rotateOneStep);
timer->start(20);
setWindowTitle(tr("Textures"));

View File

@ -39,13 +39,16 @@
****************************************************************************/
#include <QApplication>
#include <QDesktopWidget>
#include "screenshot.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Screenshot screenshot;
screenshot.move(QApplication::desktop()->availableGeometry(&screenshot).topLeft() + QPoint(20, 20));
screenshot.show();
return app.exec();
}

View File

@ -44,20 +44,48 @@
//! [0]
Screenshot::Screenshot()
: screenshotLabel(new QLabel(this))
{
screenshotLabel = new QLabel;
screenshotLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
screenshotLabel->setAlignment(Qt::AlignCenter);
screenshotLabel->setMinimumSize(240, 160);
createOptionsGroupBox();
createButtonsLayout();
const QRect screenGeometry = QApplication::desktop()->screenGeometry(this);
screenshotLabel->setMinimumSize(screenGeometry.width() / 8, screenGeometry.height() / 8);
mainLayout = new QVBoxLayout;
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(screenshotLabel);
QGroupBox *optionsGroupBox = new QGroupBox(tr("Options"), this);
delaySpinBox = new QSpinBox(optionsGroupBox);
delaySpinBox->setSuffix(tr(" s"));
delaySpinBox->setMaximum(60);
typedef void (QSpinBox::*QSpinBoxIntSignal)(int);
connect(delaySpinBox, static_cast<QSpinBoxIntSignal>(&QSpinBox::valueChanged),
this, &Screenshot::updateCheckBox);
hideThisWindowCheckBox = new QCheckBox(tr("Hide This Window"), optionsGroupBox);
QGridLayout *optionsGroupBoxLayout = new QGridLayout(optionsGroupBox);
optionsGroupBoxLayout->addWidget(new QLabel(tr("Screenshot Delay:"), this), 0, 0);
optionsGroupBoxLayout->addWidget(delaySpinBox, 0, 1);
optionsGroupBoxLayout->addWidget(hideThisWindowCheckBox, 1, 0, 1, 2);
mainLayout->addWidget(optionsGroupBox);
QHBoxLayout *buttonsLayout = new QHBoxLayout;
newScreenshotButton = new QPushButton(tr("New Screenshot"), this);
connect(newScreenshotButton, &QPushButton::clicked, this, &Screenshot::newScreenshot);
buttonsLayout->addWidget(newScreenshotButton);
QPushButton *saveScreenshotButton = new QPushButton(tr("Save Screenshot"), this);
connect(saveScreenshotButton, &QPushButton::clicked, this, &Screenshot::saveScreenshot);
buttonsLayout->addWidget(saveScreenshotButton);
QPushButton *quitScreenshotButton = new QPushButton(tr("Quit"), this);
quitScreenshotButton->setShortcut(Qt::CTRL + Qt::Key_Q);
connect(quitScreenshotButton, &QPushButton::clicked, this, &QWidget::close);
buttonsLayout->addWidget(quitScreenshotButton);
buttonsLayout->addStretch();
mainLayout->addLayout(buttonsLayout);
setLayout(mainLayout);
shootScreen();
delaySpinBox->setValue(5);
@ -84,44 +112,59 @@ void Screenshot::newScreenshot()
hide();
newScreenshotButton->setDisabled(true);
QTimer::singleShot(delaySpinBox->value() * 1000, this, SLOT(shootScreen()));
QTimer::singleShot(delaySpinBox->value() * 1000, this, &Screenshot::shootScreen);
}
//! [2]
//! [3]
void Screenshot::saveScreenshot()
{
QString format = "png";
QString initialPath = QDir::currentPath() + tr("/untitled.") + format;
const QString format = "png";
QString initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
if (initialPath.isEmpty())
initialPath = QDir::currentPath();
initialPath += tr("/untitled.") + format;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(format.toUpper())
.arg(format));
if (!fileName.isEmpty())
originalPixmap.save(fileName, format.toLatin1().constData());
QFileDialog fileDialog(this, tr("Save As"), initialPath);
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setFileMode(QFileDialog::AnyFile);
fileDialog.setDirectory(initialPath);
QStringList mimeTypes;
foreach (const QByteArray &bf, QImageWriter::supportedMimeTypes())
mimeTypes.append(QLatin1String(bf));
fileDialog.setMimeTypeFilters(mimeTypes);
fileDialog.selectMimeTypeFilter("image/" + format);
fileDialog.setDefaultSuffix(format);
if (fileDialog.exec() != QDialog::Accepted)
return;
const QString fileName = fileDialog.selectedFiles().first();
if (!originalPixmap.save(fileName)) {
QMessageBox::warning(this, tr("Save Error"), tr("The image could not be saved to \"%1\".")
.arg(QDir::toNativeSeparators(fileName)));
}
}
//! [3]
//! [4]
void Screenshot::shootScreen()
{
if (delaySpinBox->value() != 0)
qApp->beep();
//! [4]
originalPixmap = QPixmap(); // clear image for low memory situations
// on embedded devices.
//! [5]
QScreen *screen = QGuiApplication::primaryScreen();
if (screen)
originalPixmap = screen->grabWindow(0);
if (const QWindow *window = windowHandle())
screen = window->screen();
if (!screen)
return;
if (delaySpinBox->value() != 0)
QApplication::beep();
originalPixmap = screen->grabWindow(0);
updateScreenshotLabel();
newScreenshotButton->setDisabled(false);
if (hideThisWindowCheckBox->isChecked())
show();
}
//! [5]
//! [4]
//! [6]
void Screenshot::updateCheckBox()
@ -135,52 +178,6 @@ void Screenshot::updateCheckBox()
}
//! [6]
//! [7]
void Screenshot::createOptionsGroupBox()
{
optionsGroupBox = new QGroupBox(tr("Options"));
delaySpinBox = new QSpinBox;
delaySpinBox->setSuffix(tr(" s"));
delaySpinBox->setMaximum(60);
connect(delaySpinBox, SIGNAL(valueChanged(int)), this, SLOT(updateCheckBox()));
delaySpinBoxLabel = new QLabel(tr("Screenshot Delay:"));
hideThisWindowCheckBox = new QCheckBox(tr("Hide This Window"));
optionsGroupBoxLayout = new QGridLayout;
optionsGroupBoxLayout->addWidget(delaySpinBoxLabel, 0, 0);
optionsGroupBoxLayout->addWidget(delaySpinBox, 0, 1);
optionsGroupBoxLayout->addWidget(hideThisWindowCheckBox, 1, 0, 1, 2);
optionsGroupBox->setLayout(optionsGroupBoxLayout);
}
//! [7]
//! [8]
void Screenshot::createButtonsLayout()
{
newScreenshotButton = createButton(tr("New Screenshot"), this, SLOT(newScreenshot()));
saveScreenshotButton = createButton(tr("Save Screenshot"), this, SLOT(saveScreenshot()));
quitScreenshotButton = createButton(tr("Quit"), this, SLOT(close()));
buttonsLayout = new QHBoxLayout;
buttonsLayout->addStretch();
buttonsLayout->addWidget(newScreenshotButton);
buttonsLayout->addWidget(saveScreenshotButton);
buttonsLayout->addWidget(quitScreenshotButton);
}
//! [8]
//! [9]
QPushButton *Screenshot::createButton(const QString &text, QWidget *receiver,
const char *member)
{
QPushButton *button = new QPushButton(text);
button->connect(button, SIGNAL(clicked()), receiver, member);
return button;
}
//! [9]
//! [10]
void Screenshot::updateScreenshotLabel()

View File

@ -73,25 +73,14 @@ private slots:
void updateCheckBox();
private:
void createOptionsGroupBox();
void createButtonsLayout();
QPushButton *createButton(const QString &text, QWidget *receiver, const char *member);
void updateScreenshotLabel();
QPixmap originalPixmap;
QLabel *screenshotLabel;
QGroupBox *optionsGroupBox;
QSpinBox *delaySpinBox;
QLabel *delaySpinBoxLabel;
QCheckBox *hideThisWindowCheckBox;
QPushButton *newScreenshotButton;
QPushButton *saveScreenshotButton;
QPushButton *quitScreenshotButton;
QVBoxLayout *mainLayout;
QGridLayout *optionsGroupBoxLayout;
QHBoxLayout *buttonsLayout;
};
//! [0]

View File

@ -42,11 +42,11 @@
#ifndef QT_NO_SYSTEMTRAYICON
#include <QtGui>
#include <QAction>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QCloseEvent>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
@ -68,12 +68,13 @@ Window::Window()
createActions();
createTrayIcon();
connect(showMessageButton, SIGNAL(clicked()), this, SLOT(showMessage()));
connect(showIconCheckBox, SIGNAL(toggled(bool)), trayIcon, SLOT(setVisible(bool)));
connect(iconComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setIcon(int)));
connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked()));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
connect(showMessageButton, &QAbstractButton::clicked, this, &Window::showMessage);
connect(showIconCheckBox, &QAbstractButton::toggled, trayIcon, &QSystemTrayIcon::setVisible);
typedef void (QComboBox::*QComboIntSignal)(int);
connect(iconComboBox, static_cast<QComboIntSignal>(&QComboBox::currentIndexChanged),
this, &Window::setIcon);
connect(trayIcon, &QSystemTrayIcon::messageClicked, this, &Window::messageClicked);
connect(trayIcon, &QSystemTrayIcon::activated, this, &Window::iconActivated);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(iconGroupBox);
@ -245,16 +246,16 @@ void Window::createMessageGroupBox()
void Window::createActions()
{
minimizeAction = new QAction(tr("Mi&nimize"), this);
connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
connect(minimizeAction, &QAction::triggered, this, &QWidget::hide);
maximizeAction = new QAction(tr("Ma&ximize"), this);
connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
connect(maximizeAction, &QAction::triggered, this, &QWidget::showMaximized);
restoreAction = new QAction(tr("&Restore"), this);
connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
connect(restoreAction, &QAction::triggered, this, &QWidget::showNormal);
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
}
void Window::createTrayIcon()

View File

@ -242,6 +242,10 @@ Dialog::Dialog(QWidget *parent)
layout->addWidget(fontLabel, 0, 1);
fontDialogOptionsWidget = new DialogOptionsWidget;
fontDialogOptionsWidget->addCheckBox(doNotUseNativeDialog, QFontDialog::DontUseNativeDialog);
fontDialogOptionsWidget->addCheckBox(tr("Show scalable fonts"), QFontDialog::ScalableFonts);
fontDialogOptionsWidget->addCheckBox(tr("Show non scalable fonts"), QFontDialog::NonScalableFonts);
fontDialogOptionsWidget->addCheckBox(tr("Show monospaced fonts"), QFontDialog::MonospacedFonts);
fontDialogOptionsWidget->addCheckBox(tr("Show proportional fonts"), QFontDialog::ProportionalFonts);
fontDialogOptionsWidget->addCheckBox(tr("No buttons") , QFontDialog::NoButtons);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 1, 0);
layout->addWidget(fontDialogOptionsWidget, 2, 0, 1 ,2);
@ -266,6 +270,7 @@ Dialog::Dialog(QWidget *parent)
fileDialogOptionsWidget->addCheckBox(tr("Do not use sheet"), QFileDialog::DontUseSheet);
fileDialogOptionsWidget->addCheckBox(tr("Readonly"), QFileDialog::ReadOnly);
fileDialogOptionsWidget->addCheckBox(tr("Hide name filter details"), QFileDialog::HideNameFilterDetails);
fileDialogOptionsWidget->addCheckBox(tr("Do not use custom directory icons (Windows)"), QFileDialog::DontUseCustomDirectoryIcons);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 4, 0);
layout->addWidget(fileDialogOptionsWidget, 5, 0, 1 ,2);
toolbox->addItem(page, tr("File Dialogs"));

View File

@ -39,6 +39,7 @@
****************************************************************************/
#include <QApplication>
#include <QDesktopWidget>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
@ -58,6 +59,10 @@ int main(int argc, char *argv[])
#endif
Dialog dialog;
const QRect availableGeometry = QApplication::desktop()->availableGeometry(&dialog);
dialog.resize(availableGeometry.width() / 3, availableGeometry.height() * 2 / 3);
dialog.move((availableGeometry.width() - dialog.width()) / 2,
(availableGeometry.height() - dialog.height()) / 2);
dialog.show();
return app.exec();

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

View File

@ -254,6 +254,21 @@
generated pixmaps corresponding to an icon's possible states and
modes at a given size.
\snippet widgets/icons/iconpreviewarea.cpp 42
We would like the table columns to be in the order QIcon::Normal,
QIcon::Active, QIcon::Disabled, QIcon::Selected and the rows in the order
QIcon::Off, QIcon::On, which does not match the enumeration. The above code
provides arrays allowing to map from enumeration value to row/column
(by using QVector::indexOf()) and back by using the array index and lists
of the matching strings. Qt's containers can be easily populated by
using C++ 11 initializer lists. If the compiler does not provide that feature,
a pattern like
\snippet widgets/icons/iconpreviewarea.cpp 43
can be used.
We need two public functions to set the current icon and the
icon's size. In addition the class has three private functions: We
use the \c createHeaderLabel() and \c createPixmapLabel()
@ -326,7 +341,12 @@
For each mode, and for each state, we retrieve a pixmap using the
QIcon::pixmap() function, which generates a pixmap corresponding
to the given state, mode and size.
to the given state, mode and size. We pass the QWindows instance
obtained by calling QWidget::windowHandle() on the top level
widget (QWidget::nativeParentWidget()) in order to retrieve
the pixmap that matches best.
We format a tooltip displaying size, actual size and device pixel
ratio.
\section2 MainWindow Class Definition
@ -347,8 +367,14 @@
\li The \c changeSize() slot changes the size of the preview area's icon.
\li The \c changeIcon() slot updates the set of pixmaps available to the
icon displayed in the preview area.
\li The \c addImage() slot allows the user to load a new image into the
application.
\li The \c addSampleImages() slot allows the user to load a new image
from the samples provided into the application.
\li The \c addOtherImages() slot allows the user to load a new image from
the directory obtained by calling
QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).
\li The \c screenChanged() updates the display in the \uicontrol{High DPI}
group box to correctly display the parameters of the current screen
the window is located on.
\endlist
In addition we declare several private functions to simplify the
@ -362,8 +388,7 @@
widget and its child widgets, and put them in a grid layout. Then
we create the menus with their associated entries and actions.
Before we resize the application window to a suitable size, we set
the window title and determine the current style for the
We set the window title and determine the current style for the
application. We also enable the icon size spin box by clicking the
associated radio button, making the current value of the spin box
the icon's initial size.
@ -421,21 +446,27 @@
The \c changeSize() slot sets the size for the preview area's
icon.
To determine the new size we first check if the spin box is
It is invoked by the QButtonGroup whose members are radio buttons for
controlling the icon size. In \c createIconSizeGroupBox(), each button is
assigned a QStyle::PixelMetric value as an id, which is passed as a
parameter to the slot.
The special value \c OtherSize indicates that the spin box is
enabled. If it is, we extract the extent of the new size from the
box. If it's not, we search through the predefined size options,
extract the QStyle::PixelMetric and use the QStyle::pixelMetric()
function to determine the extent. Then we create a QSize object
based on the extent, and use that object to set the size of the
preview area's icon.
box. If it's not, we query the style for the metric. Then we create
a QSize object based on the extent, and use that object to set the
size of the preview area's icon.
\snippet widgets/icons/mainwindow.cpp 12
The first thing we do when the \c addImage() slot is called, is to
show a file dialog to the user. The easiest way to create a file
dialog is to use QFileDialog's static functions. Here we use the
\l {QFileDialog::getOpenFileNames()}{getOpenFileNames()} function
that will return one or more existing files selected by the user.
The function \c addImages() is called by the slot addSampleImages()
passing the samples directory, or by the slot addOtherImages()
passing the directory obtained by querying
QStandardPaths::standardLocations().
The first thing we do is to show a file dialog to the user.
We initialize it to show the filters returned by
QImageReader::supportedMimeTypes().
For each of the files the file dialog returns, we add a row to the
table widget. The table widget is listing the images the user has
@ -446,9 +477,13 @@
We retrieve the image name using the QFileInfo::baseName()
function that returns the base name of the file without the path,
and create the first table widget item in the row. Then we add the
file's complete name to the item's data. Since an item can hold
several information pieces, we need to assign the file name a role
and create the first table widget item in the row.
We check if a high resolution version of the image exists (identified by
the suffix \c @2x on the base name) and display that along with the size
in the tooltip.
We add the file's complete name to the item's data. Since an item can
hold several information pieces, we need to assign the file name a role
that will distinguish it from other data. This role can be Qt::UserRole
or any value above it.
@ -465,7 +500,7 @@
contains "_act", "_dis", or "_sel", the modes are changed to
Active, Disabled, or Selected. And if the file name contains
"_on", the state is changed to On. The sample files in the
example's \c images subdirectory respect this naming convension.
example's \c images subdirectory respect this naming convention.
\snippet widgets/icons/mainwindow.cpp 18
\snippet widgets/icons/mainwindow.cpp 19
@ -482,7 +517,6 @@
make sure that the new image's check box is enabled.
\snippet widgets/icons/mainwindow.cpp 6
\snippet widgets/icons/mainwindow.cpp 7
The \c changeIcon() slot is called when the user alters the set
of images listed in the QTableWidget, to update the QIcon object
@ -562,7 +596,7 @@
\snippet widgets/icons/mainwindow.cpp 25
At the end, we connect the QTableWidget::itemChanged() signal to
the \c changeIcon() slot to ensuret that the preview area is in
the \c changeIcon() slot to ensure that the preview area is in
sync with the image table.
\image icons_size_groupbox.png Screenshot of the icon size group box
@ -574,7 +608,14 @@
\snippet widgets/icons/mainwindow.cpp 26
First we create a group box that will contain all the widgets;
then we create the radio buttons and the spin box.
then we create the radio buttons and the spin box. We add the
radio buttons to an instance of QButtonGroup, using the value
of the QStyle::PixelMetric they represent as an integer id.
\snippet widgets/icons/mainwindow.cpp 40
We introduce an enumeration constant \c OtherSize to represent
a custom size.
The spin box is not a regular QSpinBox but an \c IconSizeSpinBox.
The \c IconSizeSpinBox class inherits QSpinBox and reimplements
@ -602,19 +643,16 @@
In particular we create the \c styleActionGroup based on the
currently available GUI styles using
QStyleFactory. QStyleFactory::keys() returns a list of valid keys,
typically including "windows", "cleanlooks" and
"plastique". Depending on the platform, "windowsxp", "windowsvista", "gtk" and
"macintosh" may be available.
typically including "windows" and "fusion". Depending on the platform,
"windowsvista" and "macintosh" may be available.
We create one action for each key, and adds the action to the
action group. Also, for each action, we call QAction::setData()
with the style name. We will retrieve it later using
QAction::data().
\snippet widgets/icons/mainwindow.cpp 29
In the \c createMenu() function, we add the previously created
actions to the \uicontrol File, \uicontrol View and \uicontrol Help menus.
As we go along, we create the \uicontrol File, \uicontrol View and
\uicontrol Help menus and add the actions to them.
The QMenu class provides a menu widget for use in menu bars,
context menus, and other popup menus. We put each menu in the
@ -656,6 +694,13 @@
Q_ASSERT() macro to make sure that QStyleFactory::create()
returned a valid pointer.
\snippet widgets/icons/mainwindow.cpp 44
We overload the show() function to set up the updating of the
current screen in \c screenChanged(). After calling QWidget::show(),
the QWindow associated with the QWidget is created and we can
connect to its QWindow::screenChanged() signal.
\section2 IconSizeSpinBox Class Definition
\snippet widgets/icons/iconsizespinbox.h 0
@ -690,7 +735,7 @@
reimplement the \c valueFromText() function to interpret the
parameter text and return the associated int value.
We parse the text using a regular expression (a QRegExp). We
We parse the text using a regular expression (a QRegularExpression). We
define an expression that matches one or several digits,
optionally followed by whitespace, an "x" or the times symbol,
whitespace and one or several digits again.
@ -748,7 +793,7 @@
index for editing. The parent widget and style option are used to
control the appearance of the editor widget.
Our reimplementation create and populate a combobox instead of
Our reimplementation creates and populates a combobox instead of
the default line edit. The contents of the combobox depends on
the column in the table for which the editor is requested. Column
1 contains the QIcon modes, whereas column 2 contains the QIcon
@ -786,4 +831,12 @@
triggered the slot. This signal must be emitted when the editor
widget has completed editing the data, and wants to write it back
into the model.
\section2 The Implementation of the Function main()
\snippet widgets/icons/main.cpp 45
We use QCommandLineParser to handle any command line options or parameters
passed to the application. Then, we resize the main window according
to the available screen geometry and show it.
*/

View File

@ -287,7 +287,8 @@
\snippet widgets/imageviewer/imageviewer.cpp 18
In the private \c createAction() function, we create the
actions providing the application features.
actions providing the application features and populate
a menu with them.
We assign a short-cut key to each action and connect them to the
appropriate slots. We only enable the \c openAct and \c exitAct at
@ -295,16 +296,10 @@
been loaded into the application. In addition we make the \c
fitToWindowAct \l {QAction::checkable}{checkable}.
\snippet widgets/imageviewer/imageviewer.cpp 19
\snippet widgets/imageviewer/imageviewer.cpp 20
In the private \c createMenu() function, we add the previously
created actions to the \uicontrol File, \uicontrol View and \uicontrol Help menus.
The QMenu class provides a menu widget for use in menu bars,
context menus, and other popup menus. The QMenuBar class provides
a horizontal menu bar that consists of a list of pull-down menu
items. So at the end we put the menus in the \c {ImageViewer}'s
items. So we put the menus in the \c {ImageViewer}'s
menu bar which we retrieve with the QMainWindow::menuBar()
function.

View File

@ -33,7 +33,7 @@
desktop.
\brief The Screenshot example shows how to take a screenshot of the
desktop using QApplication and QDesktopWidget. It also shows how
desktop using QScreen. It also shows how
to use QTimer to provide a single-shot timer, and how to
reimplement the QWidget::resizeEvent() event handler to make sure
that an application resizes smoothly and without data loss.
@ -73,12 +73,9 @@
\uicontrol {Hide This Window} option.
\endlist
We also declare some private functions: We use the \c
createOptionsGroupBox(), \c createButtonsLayout() and \c
createButton() functions when we construct the widget. And we call
the private \c updateScreenshotLabel() function whenever a new
screenshot is taken or when a resize event changes the size of the
screenshot preview label.
We also declare the private function \c updateScreenshotLabel() which
is called whenever a new screenshot is taken or when a resize event
changes the size of the screenshot preview label.
In addition we need to store the screenshot's original pixmap. The
reason is that when we display the preview of the screenshot, we
@ -100,11 +97,18 @@
aligned in the center of the \c Screenshot widget, and set its
minimum size.
Next, we create a group box that will contain all of the options'
widgets. Then we create a QSpinBox and a QLabel for the \uicontrol
{Screenshot Delay} option, and connect the spinbox to the \c
updateCheckBox() slot. Finally, we create a QCheckBox for the \uicontrol
{Hide This Window} option, add all the options' widgets to a
QGridLayout installed on the group box.
We create the applications's buttons and the group box containing
the application's options, and put it all into a main
layout. Finally we take the initial screenshot, and set the initial
delay and the window title, before we resize the widget to a
suitable size.
suitable size depending on the screen geometry.
\snippet desktop/screenshot/screenshot.cpp 1
@ -151,34 +155,37 @@
QFileDialog enables a user to traverse the file system in order to
select one or many files or a directory. The easiest way to create
a QFileDialog is to use the convenience static
functions.
functions. Here, we instantiate the dialog on the stack in order
to be able to set up the supported mime types of QImageWriter,
allowing the user to save in a variety of formats.
We define the default file format to be png, and we make the file
dialog's initial path the path the application is run from. We
create the file dialog using the static
QFileDialog::getSaveFileName() function which returns a file name
selected by the user. The file does not have to exist. If the file
dialog's initial path the location of pictures as obtained from
QStandardPaths, defaulting to the path the application is run from.
We run the dialog by invoking QDialog::exec() and return if the
user canceled the dialog. If the dialog has been accepted, we
obtain a file name by calling QFileDialog::selectedFiles().
The file does not have to exist. If the file
name is valid, we use the QPixmap::save() function to save the
screenshot's original pixmap in that file.
\snippet desktop/screenshot/screenshot.cpp 4
The \c shootScreen() slot is called to take the screenshot. If the
user has chosen to delay the screenshot, we make the application
The \c shootScreen() slot is called to take the screenshot.
First, we find the instance of QScreen the window is located
by retrieving the QWindow and its QScreen, defaulting
to the primary screen. If no screen can be found, we return.
Although this is unlikely to happen, applications should check
for null pointers since there might be situations in which no
screen is connected.
If the user has chosen to delay the screenshot, we make the application
beep when the screenshot is taken using the static
QApplication::beep() function.
The QApplication class manages the GUI application's control flow
and main settings. It contains the main event loop, where all
events from the window system and other sources are processed and
dispatched.
\snippet desktop/screenshot/screenshot.cpp 5
Using the static function QApplication::primaryScreen(), we
obtain the QScreen object for the application's main screen.
We take the screenshot using the QScreen::grabWindow()
We then take the screenshot using the QScreen::grabWindow()
function. The function grabs the contents of the window passed as
an argument, makes a pixmap out of it and returns that pixmap.
The window id can be obtained with QWidget::winId() or QWindow::winId().
@ -200,37 +207,6 @@
The \c updateCheckBox() slot is called whenever the user changes
the delay using the \uicontrol {Screenshot Delay} option.
\snippet desktop/screenshot/screenshot.cpp 7
The private \c createOptionsGroupBox() function is called from the
constructor.
First we create a group box that will contain all of the options'
widgets. Then we create a QSpinBox and a QLabel for the \uicontrol
{Screenshot Delay} option, and connect the spinbox to the \c
updateCheckBox() slot. Finally, we create a QCheckBox for the \uicontrol
{Hide This Window} option, add all the options' widgets to a
QGridLayout and install the layout on the group box.
Note that we don't have to specify any parents for the widgets
when we create them. The reason is that when we add a widget to a
layout and install the layout on another widget, the layout's
widgets are automatically reparented to the widget the layout is
installed on.
\snippet desktop/screenshot/screenshot.cpp 8
The private \c createButtonsLayout() function is called from the
constructor. We create the application's buttons using the private
\c createButton() function, and add them to a QHBoxLayout.
\snippet desktop/screenshot/screenshot.cpp 9
The private \c createButton() function is called from the \c
createButtonsLayout() function. It simply creates a QPushButton
with the provided text, connects it to the provided receiver and
slot, and returns a pointer to the button.
\snippet desktop/screenshot/screenshot.cpp 10
The private \c updateScreenshotLabel() function is called whenever

View File

@ -0,0 +1,179 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Free Documentation License Usage
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of
** this file. Please review the following information to ensure
** the GNU Free Documentation License version 1.3 requirements
** will be met: http://www.gnu.org/copyleft/fdl.html.
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\example desktop/systray
\title System Tray Icon Example
\ingroup examples-widgets
\brief The System Tray Icon example shows how to add an icon with a menu
and popup messages to a desktop environment's system tray.
\image systemtray-example.png Screenshot of the System Tray Icon.
Modern operating systems usually provide a special area on the
desktop, called the system tray or notification area, where
long-running applications can display icons and short messages.
This example consists of one single class, \c Window, providing
the main application window (i.e., an editor for the system tray
icon) and the associated icon.
\image systemtray-editor.png
The editor allows the user to choose the preferred icon as well as
set the balloon message's type and duration. The user can also
edit the message's title and body. Finally, the editor provides a
checkbox controlling whether the icon is actually shown in the
system tray, or not.
\section1 Window Class Definition
The \c Window class inherits QWidget:
\snippet desktop/systray/window.h 0
We implement several private slots to respond to user
interaction. The other private functions are only convenience
functions provided to simplify the constructor.
The tray icon is an instance of the QSystemTrayIcon class. To
check whether a system tray is present on the user's desktop, call
the static QSystemTrayIcon::isSystemTrayAvailable()
function. Associated with the icon, we provide a menu containing
the typical \uicontrol minimize, \uicontrol maximize, \uicontrol restore and
\uicontrol quit actions. We reimplement the QWidget::setVisible() function
to update the tray icon's menu whenever the editor's appearance
changes, e.g., when maximizing or minimizing the main application
window.
Finally, we reimplement QWidget's \l {QWidget::}{closeEvent()}
function to be able to inform the user (when closing the editor
window) that the program will keep running in the system tray
until the user chooses the \uicontrol Quit entry in the icon's context
menu.
\section1 Window Class Implementation
When constructing the editor widget, we first create the various
editor elements before we create the actual system tray icon:
\snippet desktop/systray/window.cpp 0
We ensure that the application responds to user input by
connecting most of the editor's input widgets (including the
system tray icon) to the application's private slots. But note the
visibility checkbox; its \l {QCheckBox::}{toggled()} signal is
connected to the \e {icon}'s \l {QSystemTrayIcon::}{setVisible()}
function instead.
\snippet desktop/systray/window.cpp 3
The \c setIcon() slot is triggered whenever the current index in
the icon combobox changes, i.e., whenever the user chooses another
icon in the editor. Note that it is also called when the user
activates the tray icon with the left mouse button, triggering the
icon's \l {QSystemTrayIcon::}{activated()} signal. We will come
back to this signal shortly.
The QSystemTrayIcon::setIcon() function sets the \l
{QSystemTrayIcon::}{icon} property that holds the actual system
tray icon. On Windows, the system tray icon size is 16x16; on X11,
the preferred size is 22x22. The icon will be scaled to the
appropriate size as necessary.
Note that on X11, due to a limitation in the system tray
specification, mouse clicks on transparent areas in the icon are
propagated to the system tray. If this behavior is unacceptable,
we suggest using an icon with no transparency.
\snippet desktop/systray/window.cpp 4
Whenever the user activates the system tray icon, it emits its \l
{QSystemTrayIcon::}{activated()} signal passing the triggering
reason as parameter. QSystemTrayIcon provides the \l
{QSystemTrayIcon::}{ActivationReason} enum to describe how the
icon was activated.
In the constructor, we connected our icon's \l
{QSystemTrayIcon::}{activated()} signal to our custom \c
iconActivated() slot: If the user has clicked the icon using the
left mouse button, this function changes the icon image by
incrementing the icon combobox's current index, triggering the \c
setIcon() slot as mentioned above. If the user activates the icon
using the middle mouse button, it calls the custom \c
showMessage() slot:
\snippet desktop/systray/window.cpp 5
When the \e showMessage() slot is triggered, we first retrieve the
message icon depending on the currently chosen message type. The
QSystemTrayIcon::MessageIcon enum describes the icon that is shown
when a balloon message is displayed. Then we call
QSystemTrayIcon's \l {QSystemTrayIcon::}{showMessage()} function
to show the message with the title, body, and icon for the time
specified in milliseconds.
QSystemTrayIcon also has the corresponding, \l {QSystemTrayIcon::}
{messageClicked()} signal, which is emitted when the user clicks a
message displayed by \l {QSystemTrayIcon::}{showMessage()}.
\snippet desktop/systray/window.cpp 6
In the constructor, we connected the \l
{QSystemTrayIcon::}{messageClicked()} signal to our custom \c
messageClicked() slot that simply displays a message using the
QMessageBox class.
QMessageBox provides a modal dialog with a short message, an icon,
and buttons laid out depending on the current style. It supports
four severity levels: "Question", "Information", "Warning" and
"Critical". The easiest way to pop up a message box in Qt is to
call one of the associated static functions, e.g.,
QMessageBox::information().
As we mentioned earlier, we reimplement a couple of QWidget's
virtual functions:
\snippet desktop/systray/window.cpp 1
Our reimplementation of the QWidget::setVisible() function updates
the tray icon's menu whenever the editor's appearance changes,
e.g., when maximizing or minimizing the main application window,
before calling the base class implementation.
\snippet desktop/systray/window.cpp 2
We have reimplemented the QWidget::closeEvent() event handler to
receive widget close events, showing the above message to the
users when they are closing the editor window.
In addition to the functions and slots discussed above, we have
also implemented several convenience functions to simplify the
constructor: \c createIconGroupBox(), \c createMessageGroupBox(),
\c createActions() and \c createTrayIcon(). See the \l
{desktop/systray/window.cpp}{window.cpp} file for details.
*/

View File

@ -108,7 +108,7 @@
We connect \l{QAbstractButton::}{clicked()} signals from the \uicontrol{Start}
and \uicontrol{Pause} buttons to the board, and from the \uicontrol{Quit} button to the
application's \l{QApplication::}{quit()} slot.
application's \l{QCoreApplication::quit()} slot.
\snippet widgets/tetrix/tetrixwindow.cpp 4
\snippet widgets/tetrix/tetrixwindow.cpp 5

View File

@ -32,15 +32,37 @@
****************************************************************************/
#include "textedit.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QCommandLineParser>
#include <QCommandLineOption>
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(textedit);
QApplication a(argc, argv);
QCoreApplication::setOrganizationName("QtProject");
QCoreApplication::setApplicationName("Rich Text");
QCoreApplication::setApplicationVersion(QT_VERSION_STR);
QCommandLineParser parser;
parser.setApplicationDescription(QCoreApplication::applicationName());
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("file", "The file to open.");
parser.process(a);
TextEdit mw;
mw.resize(700, 800);
const QRect availableGeometry = QApplication::desktop()->availableGeometry(&mw);
mw.resize(availableGeometry.width() / 2, (availableGeometry.height() * 2) / 3);
mw.move((availableGeometry.width() - mw.width()) / 2,
(availableGeometry.height() - mw.height()) / 2);
if (!mw.load(parser.positionalArguments().value(0, QLatin1String(":/example.html"))))
mw.fileNew();
mw.show();
return a.exec();
}

View File

@ -45,6 +45,7 @@
#include <QMenuBar>
#include <QTextCodec>
#include <QTextEdit>
#include <QStatusBar>
#include <QToolBar>
#include <QTextCursor>
#include <QTextDocumentWriter>
@ -73,6 +74,14 @@ TextEdit::TextEdit(QWidget *parent)
#ifdef Q_OS_OSX
setUnifiedTitleAndToolBarOnMac(true);
#endif
setWindowTitle(QCoreApplication::applicationName());
textEdit = new QTextEdit(this);
connect(textEdit, &QTextEdit::currentCharFormatChanged,
this, &TextEdit::currentCharFormatChanged);
connect(textEdit, &QTextEdit::cursorPositionChanged,
this, &TextEdit::cursorPositionChanged);
setCentralWidget(textEdit);
setToolButtonStyle(Qt::ToolButtonFollowStyle);
setupFileActions();
@ -80,22 +89,11 @@ TextEdit::TextEdit(QWidget *parent)
setupTextActions();
{
QMenu *helpMenu = new QMenu(tr("Help"), this);
menuBar()->addMenu(helpMenu);
helpMenu->addAction(tr("About"), this, SLOT(about()));
helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
QMenu *helpMenu = menuBar()->addMenu(tr("Help"));
helpMenu->addAction(tr("About"), this, &TextEdit::about);
helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
}
textEdit = new QTextEdit(this);
connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
this, SLOT(currentCharFormatChanged(QTextCharFormat)));
connect(textEdit, SIGNAL(cursorPositionChanged()),
this, SLOT(cursorPositionChanged()));
setCentralWidget(textEdit);
textEdit->setFocus();
setCurrentFileName(QString());
QFont textFont("Helvetica");
textFont.setStyleHint(QFont::SansSerif);
textEdit->setFont(textFont);
@ -103,44 +101,29 @@ TextEdit::TextEdit(QWidget *parent)
colorChanged(textEdit->textColor());
alignmentChanged(textEdit->alignment());
connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
actionSave, SLOT(setEnabled(bool)));
connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
this, SLOT(setWindowModified(bool)));
connect(textEdit->document(), SIGNAL(undoAvailable(bool)),
actionUndo, SLOT(setEnabled(bool)));
connect(textEdit->document(), SIGNAL(redoAvailable(bool)),
actionRedo, SLOT(setEnabled(bool)));
connect(textEdit->document(), &QTextDocument::modificationChanged,
actionSave, &QAction::setEnabled);
connect(textEdit->document(), &QTextDocument::modificationChanged,
this, &QWidget::setWindowModified);
connect(textEdit->document(), &QTextDocument::undoAvailable,
actionUndo, &QAction::setEnabled);
connect(textEdit->document(), &QTextDocument::redoAvailable,
actionRedo, &QAction::setEnabled);
setWindowModified(textEdit->document()->isModified());
actionSave->setEnabled(textEdit->document()->isModified());
actionUndo->setEnabled(textEdit->document()->isUndoAvailable());
actionRedo->setEnabled(textEdit->document()->isRedoAvailable());
connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo()));
connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo()));
actionCut->setEnabled(false);
actionCopy->setEnabled(false);
connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut()));
connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy()));
connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste()));
connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool)));
connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool)));
#ifndef QT_NO_CLIPBOARD
connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &TextEdit::clipboardDataChanged);
#endif
QString initialFile = ":/example.html";
const QStringList args = QCoreApplication::arguments();
if (args.count() == 2)
initialFile = args.at(1);
if (!load(initialFile))
fileNew();
textEdit->setFocus();
setCurrentFileName(QString());
}
void TextEdit::closeEvent(QCloseEvent *e)
@ -153,116 +136,89 @@ void TextEdit::closeEvent(QCloseEvent *e)
void TextEdit::setupFileActions()
{
QToolBar *tb = new QToolBar(this);
tb->setWindowTitle(tr("File Actions"));
addToolBar(tb);
QToolBar *tb = addToolBar(tr("File Actions"));
QMenu *menu = menuBar()->addMenu(tr("&File"));
QMenu *menu = new QMenu(tr("&File"), this);
menuBar()->addMenu(menu);
QAction *a;
QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png"));
a = new QAction( newIcon, tr("&New"), this);
const QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png"));
QAction *a = menu->addAction(newIcon, tr("&New"), this, &TextEdit::fileNew);
tb->addAction(a);
a->setPriority(QAction::LowPriority);
a->setShortcut(QKeySequence::New);
connect(a, SIGNAL(triggered()), this, SLOT(fileNew()));
tb->addAction(a);
menu->addAction(a);
a = new QAction(QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png")),
tr("&Open..."), this);
const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png"));
a = menu->addAction(openIcon, tr("&Open..."), this, &TextEdit::fileOpen);
a->setShortcut(QKeySequence::Open);
connect(a, SIGNAL(triggered()), this, SLOT(fileOpen()));
tb->addAction(a);
menu->addAction(a);
menu->addSeparator();
actionSave = a = new QAction(QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png")),
tr("&Save"), this);
a->setShortcut(QKeySequence::Save);
connect(a, SIGNAL(triggered()), this, SLOT(fileSave()));
a->setEnabled(false);
tb->addAction(a);
menu->addAction(a);
const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png"));
actionSave = menu->addAction(saveIcon, tr("&Save"), this, &TextEdit::fileSave);
actionSave->setShortcut(QKeySequence::Save);
actionSave->setEnabled(false);
tb->addAction(actionSave);
a = new QAction(tr("Save &As..."), this);
a = menu->addAction(tr("Save &As..."), this, &TextEdit::fileSaveAs);
a->setPriority(QAction::LowPriority);
connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs()));
menu->addAction(a);
menu->addSeparator();
#ifndef QT_NO_PRINTER
a = new QAction(QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png")),
tr("&Print..."), this);
const QIcon printIcon = QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png"));
a = menu->addAction(printIcon, tr("&Print..."), this, &TextEdit::filePrint);
a->setPriority(QAction::LowPriority);
a->setShortcut(QKeySequence::Print);
connect(a, SIGNAL(triggered()), this, SLOT(filePrint()));
tb->addAction(a);
menu->addAction(a);
a = new QAction(QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png")),
tr("Print Preview..."), this);
connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview()));
menu->addAction(a);
const QIcon filePrintIcon = QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png"));
menu->addAction(filePrintIcon, tr("Print Preview..."), this, &TextEdit::filePrintPreview);
a = new QAction(QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png")),
tr("&Export PDF..."), this);
const QIcon exportPdfIcon = QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png"));
a = menu->addAction(exportPdfIcon, tr("&Export PDF..."), this, &TextEdit::filePrintPdf);
a->setPriority(QAction::LowPriority);
a->setShortcut(Qt::CTRL + Qt::Key_D);
connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf()));
tb->addAction(a);
menu->addAction(a);
menu->addSeparator();
#endif
a = new QAction(tr("&Quit"), this);
a = menu->addAction(tr("&Quit"), this, &QWidget::close);
a->setShortcut(Qt::CTRL + Qt::Key_Q);
connect(a, SIGNAL(triggered()), this, SLOT(close()));
menu->addAction(a);
}
void TextEdit::setupEditActions()
{
QToolBar *tb = new QToolBar(this);
tb->setWindowTitle(tr("Edit Actions"));
addToolBar(tb);
QMenu *menu = new QMenu(tr("&Edit"), this);
menuBar()->addMenu(menu);
QToolBar *tb = addToolBar(tr("Edit Actions"));
QMenu *menu = menuBar()->addMenu(tr("&Edit"));
QAction *a;
a = actionUndo = new QAction(QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png")),
tr("&Undo"), this);
a->setShortcut(QKeySequence::Undo);
tb->addAction(a);
menu->addAction(a);
a = actionRedo = new QAction(QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png")),
tr("&Redo"), this);
a->setPriority(QAction::LowPriority);
a->setShortcut(QKeySequence::Redo);
tb->addAction(a);
menu->addAction(a);
const QIcon undoIcon = QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png"));
actionUndo = menu->addAction(undoIcon, tr("&Undo"), textEdit, &QTextEdit::undo);
actionUndo->setShortcut(QKeySequence::Undo);
tb->addAction(actionUndo);
const QIcon redoIcon = QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png"));
actionRedo = menu->addAction(redoIcon, tr("&Redo"), textEdit, &QTextEdit::redo);
actionRedo->setPriority(QAction::LowPriority);
actionRedo->setShortcut(QKeySequence::Redo);
tb->addAction(actionRedo);
menu->addSeparator();
a = actionCut = new QAction(QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png")),
tr("Cu&t"), this);
a->setPriority(QAction::LowPriority);
a->setShortcut(QKeySequence::Cut);
tb->addAction(a);
menu->addAction(a);
a = actionCopy = new QAction(QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png")),
tr("&Copy"), this);
a->setPriority(QAction::LowPriority);
a->setShortcut(QKeySequence::Copy);
tb->addAction(a);
menu->addAction(a);
a = actionPaste = new QAction(QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png")),
tr("&Paste"), this);
a->setPriority(QAction::LowPriority);
a->setShortcut(QKeySequence::Paste);
tb->addAction(a);
menu->addAction(a);
const QIcon cutIcon = QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png"));
actionCut = menu->addAction(cutIcon, tr("Cu&t"), textEdit, &QTextEdit::cut);
actionCut->setPriority(QAction::LowPriority);
actionCut->setShortcut(QKeySequence::Cut);
tb->addAction(actionCut);
const QIcon copyIcon = QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png"));
actionCopy = menu->addAction(copyIcon, tr("&Copy"), textEdit, &QTextEdit::copy);
actionCopy->setPriority(QAction::LowPriority);
actionCopy->setShortcut(QKeySequence::Copy);
tb->addAction(actionCopy);
const QIcon pasteIcon = QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png"));
actionPaste = menu->addAction(pasteIcon, tr("&Paste"), textEdit, &QTextEdit::paste);
actionPaste->setPriority(QAction::LowPriority);
actionPaste->setShortcut(QKeySequence::Paste);
tb->addAction(actionPaste);
#ifndef QT_NO_CLIPBOARD
if (const QMimeData *md = QApplication::clipboard()->mimeData())
actionPaste->setEnabled(md->hasText());
@ -271,110 +227,89 @@ void TextEdit::setupEditActions()
void TextEdit::setupTextActions()
{
QToolBar *tb = new QToolBar(this);
tb->setWindowTitle(tr("Format Actions"));
addToolBar(tb);
QToolBar *tb = addToolBar(tr("Format Actions"));
QMenu *menu = menuBar()->addMenu(tr("F&ormat"));
QMenu *menu = new QMenu(tr("F&ormat"), this);
menuBar()->addMenu(menu);
actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png")),
tr("&Bold"), this);
const QIcon boldIcon = QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png"));
actionTextBold = menu->addAction(boldIcon, tr("&Bold"), this, &TextEdit::textBold);
actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
actionTextBold->setPriority(QAction::LowPriority);
QFont bold;
bold.setBold(true);
actionTextBold->setFont(bold);
connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold()));
tb->addAction(actionTextBold);
menu->addAction(actionTextBold);
actionTextBold->setCheckable(true);
actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic",
QIcon(rsrcPath + "/textitalic.png")),
tr("&Italic"), this);
const QIcon italicIcon = QIcon::fromTheme("format-text-italic", QIcon(rsrcPath + "/textitalic.png"));
actionTextItalic = menu->addAction(italicIcon, tr("&Italic"), this, &TextEdit::textItalic);
actionTextItalic->setPriority(QAction::LowPriority);
actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
QFont italic;
italic.setItalic(true);
actionTextItalic->setFont(italic);
connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic()));
tb->addAction(actionTextItalic);
menu->addAction(actionTextItalic);
actionTextItalic->setCheckable(true);
actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline",
QIcon(rsrcPath + "/textunder.png")),
tr("&Underline"), this);
const QIcon underlineIcon = QIcon::fromTheme("format-text-underline", QIcon(rsrcPath + "/textunder.png"));
actionTextUnderline = menu->addAction(underlineIcon, tr("&Underline"), this, &TextEdit::textUnderline);
actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
actionTextUnderline->setPriority(QAction::LowPriority);
QFont underline;
underline.setUnderline(true);
actionTextUnderline->setFont(underline);
connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline()));
tb->addAction(actionTextUnderline);
menu->addAction(actionTextUnderline);
actionTextUnderline->setCheckable(true);
menu->addSeparator();
QActionGroup *grp = new QActionGroup(this);
connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*)));
// Make sure the alignLeft is always left of the alignRight
if (QApplication::isLeftToRight()) {
actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left",
QIcon(rsrcPath + "/textleft.png")),
tr("&Left"), grp);
actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center",
QIcon(rsrcPath + "/textcenter.png")),
tr("C&enter"), grp);
actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right",
QIcon(rsrcPath + "/textright.png")),
tr("&Right"), grp);
} else {
actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right",
QIcon(rsrcPath + "/textright.png")),
tr("&Right"), grp);
actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center",
QIcon(rsrcPath + "/textcenter.png")),
tr("C&enter"), grp);
actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left",
QIcon(rsrcPath + "/textleft.png")),
tr("&Left"), grp);
}
actionAlignJustify = new QAction(QIcon::fromTheme("format-justify-fill",
QIcon(rsrcPath + "/textjustify.png")),
tr("&Justify"), grp);
const QIcon leftIcon = QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png"));
actionAlignLeft = new QAction(leftIcon, tr("&Left"), this);
actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L);
actionAlignLeft->setCheckable(true);
actionAlignLeft->setPriority(QAction::LowPriority);
const QIcon centerIcon = QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png"));
actionAlignCenter = new QAction(centerIcon, tr("C&enter"), this);
actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E);
actionAlignCenter->setCheckable(true);
actionAlignCenter->setPriority(QAction::LowPriority);
const QIcon rightIcon = QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png"));
actionAlignRight = new QAction(rightIcon, tr("&Right"), this);
actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R);
actionAlignRight->setCheckable(true);
actionAlignRight->setPriority(QAction::LowPriority);
const QIcon fillIcon = QIcon::fromTheme("format-justify-fill", QIcon(rsrcPath + "/textjustify.png"));
actionAlignJustify = new QAction(fillIcon, tr("&Justify"), this);
actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J);
actionAlignJustify->setCheckable(true);
actionAlignJustify->setPriority(QAction::LowPriority);
tb->addActions(grp->actions());
menu->addActions(grp->actions());
// Make sure the alignLeft is always left of the alignRight
QActionGroup *alignGroup = new QActionGroup(this);
connect(alignGroup, &QActionGroup::triggered, this, &TextEdit::textAlign);
if (QApplication::isLeftToRight()) {
alignGroup->addAction(actionAlignLeft);
alignGroup->addAction(actionAlignCenter);
alignGroup->addAction(actionAlignRight);
} else {
alignGroup->addAction(actionAlignRight);
alignGroup->addAction(actionAlignCenter);
alignGroup->addAction(actionAlignLeft);
}
alignGroup->addAction(actionAlignJustify);
tb->addActions(alignGroup->actions());
menu->addActions(alignGroup->actions());
menu->addSeparator();
QPixmap pix(16, 16);
pix.fill(Qt::black);
actionTextColor = new QAction(pix, tr("&Color..."), this);
connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor()));
actionTextColor = menu->addAction(pix, tr("&Color..."), this, &TextEdit::textColor);
tb->addAction(actionTextColor);
menu->addAction(actionTextColor);
tb = new QToolBar(this);
tb = addToolBar(tr("Format Actions"));
tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
tb->setWindowTitle(tr("Format Actions"));
addToolBarBreak(Qt::TopToolBarArea);
addToolBar(tb);
@ -389,24 +324,26 @@ void TextEdit::setupTextActions()
comboStyle->addItem("Ordered List (Alpha upper)");
comboStyle->addItem("Ordered List (Roman lower)");
comboStyle->addItem("Ordered List (Roman upper)");
connect(comboStyle, SIGNAL(activated(int)), this, SLOT(textStyle(int)));
typedef void (QComboBox::*QComboIntSignal)(int);
connect(comboStyle, static_cast<QComboIntSignal>(&QComboBox::activated), this, &TextEdit::textStyle);
typedef void (QComboBox::*QComboStringSignal)(const QString &);
comboFont = new QFontComboBox(tb);
tb->addWidget(comboFont);
connect(comboFont, SIGNAL(activated(QString)), this, SLOT(textFamily(QString)));
connect(comboFont, static_cast<QComboStringSignal>(&QComboBox::activated), this, &TextEdit::textFamily);
comboSize = new QComboBox(tb);
comboSize->setObjectName("comboSize");
tb->addWidget(comboSize);
comboSize->setEditable(true);
QFontDatabase db;
foreach(int size, db.standardSizes())
const QList<int> standardSizes = QFontDatabase::standardSizes();
foreach (int size, standardSizes)
comboSize->addItem(QString::number(size));
comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize()));
connect(comboSize, SIGNAL(activated(QString)), this, SLOT(textSize(QString)));
comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font()
.pointSize())));
connect(comboSize, static_cast<QComboStringSignal>(&QComboBox::activated), this, &TextEdit::textSize);
}
bool TextEdit::load(const QString &f)
@ -436,11 +373,11 @@ bool TextEdit::maybeSave()
if (!textEdit->document()->isModified())
return true;
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("Application"),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
const QMessageBox::StandardButton ret =
QMessageBox::warning(this, QCoreApplication::applicationName(),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
if (ret == QMessageBox::Save)
return fileSave();
else if (ret == QMessageBox::Cancel)
@ -459,7 +396,7 @@ void TextEdit::setCurrentFileName(const QString &fileName)
else
shownName = QFileInfo(fileName).fileName();
setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text")));
setWindowTitle(tr("%1[*] - %2").arg(shownName, QCoreApplication::applicationName()));
setWindowModified(false);
}
@ -473,10 +410,17 @@ void TextEdit::fileNew()
void TextEdit::fileOpen()
{
QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),
QString(), tr("HTML-Files (*.htm *.html);;All Files (*)"));
if (!fn.isEmpty())
load(fn);
QFileDialog fileDialog(this, tr("Open File..."));
fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
fileDialog.setFileMode(QFileDialog::ExistingFile);
fileDialog.setMimeTypeFilters(QStringList() << "text/html" << "text/plain");
if (fileDialog.exec() != QDialog::Accepted)
return;
const QString fn = fileDialog.selectedFiles().first();
if (load(fn))
statusBar()->showMessage(tr("Opened \"%1\"").arg(QDir::toNativeSeparators(fn)));
else
statusBar()->showMessage(tr("Could not open \"%1\"").arg(QDir::toNativeSeparators(fn)));
}
bool TextEdit::fileSave()
@ -488,23 +432,27 @@ bool TextEdit::fileSave()
QTextDocumentWriter writer(fileName);
bool success = writer.write(textEdit->document());
if (success)
if (success) {
textEdit->document()->setModified(false);
statusBar()->showMessage(tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(fileName)));
} else {
statusBar()->showMessage(tr("Could not write to file \"%1\"")
.arg(QDir::toNativeSeparators(fileName)));
}
return success;
}
bool TextEdit::fileSaveAs()
{
QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(),
tr("ODF files (*.odt);;HTML-Files "
"(*.htm *.html);;All Files (*)"));
if (fn.isEmpty())
QFileDialog fileDialog(this, tr("Save as..."));
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
QStringList mimeTypes;
mimeTypes << "application/vnd.oasis.opendocument.text" << "text/html" << "text/plain";
fileDialog.setMimeTypeFilters(mimeTypes);
fileDialog.setDefaultSuffix("odt");
if (fileDialog.exec() != QDialog::Accepted)
return false;
if (!(fn.endsWith(".odt", Qt::CaseInsensitive)
|| fn.endsWith(".htm", Qt::CaseInsensitive)
|| fn.endsWith(".html", Qt::CaseInsensitive))) {
fn += ".odt"; // default
}
const QString fn = fileDialog.selectedFiles().first();
setCurrentFileName(fn);
return fileSave();
}
@ -528,7 +476,7 @@ void TextEdit::filePrintPreview()
#if !defined(QT_NO_PRINTER) && !defined(QT_NO_PRINTDIALOG)
QPrinter printer(QPrinter::HighResolution);
QPrintPreviewDialog preview(&printer, this);
connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*)));
connect(&preview, &QPrintPreviewDialog::paintRequested, this, &TextEdit::printPreview);
preview.exec();
#endif
}
@ -547,16 +495,19 @@ void TextEdit::filePrintPdf()
{
#ifndef QT_NO_PRINTER
//! [0]
QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
QString(), "*.pdf");
if (!fileName.isEmpty()) {
if (QFileInfo(fileName).suffix().isEmpty())
fileName.append(".pdf");
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
textEdit->document()->print(&printer);
}
QFileDialog fileDialog(this, tr("Export PDF"));
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setMimeTypeFilters(QStringList("application/pdf"));
fileDialog.setDefaultSuffix("pdf");
if (fileDialog.exec() != QDialog::Accepted)
return;
QString fileName = fileDialog.selectedFiles().first();
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
textEdit->document()->print(&printer);
statusBar()->showMessage(tr("Exported \"%1\"")
.arg(QDir::toNativeSeparators(fileName)));
//! [0]
#endif
}

View File

@ -55,19 +55,15 @@ class TextEdit : public QMainWindow
public:
TextEdit(QWidget *parent = 0);
bool load(const QString &f);
public slots:
void fileNew();
protected:
virtual void closeEvent(QCloseEvent *e) Q_DECL_OVERRIDE;
private:
void setupFileActions();
void setupEditActions();
void setupTextActions();
bool load(const QString &f);
bool maybeSave();
void setCurrentFileName(const QString &fileName);
private slots:
void fileNew();
void fileOpen();
bool fileSave();
bool fileSaveAs();
@ -92,6 +88,12 @@ private slots:
void printPreview(QPrinter *);
private:
void setupFileActions();
void setupEditActions();
void setupTextActions();
bool maybeSave();
void setCurrentFileName(const QString &fileName);
void mergeFormatOnWordOrSelection(const QTextCharFormat &format);
void fontChanged(const QFont &f);
void colorChanged(const QColor &c);

View File

@ -54,17 +54,18 @@ LocationDialog::LocationDialog(QWidget *parent)
scopeComboBox->addItem(tr("System"));
organizationComboBox = new QComboBox;
organizationComboBox->addItem(tr("Qt"));
organizationComboBox->addItem(tr("QtProject"));
organizationComboBox->setEditable(true);
applicationComboBox = new QComboBox;
applicationComboBox->addItem(tr("Any"));
applicationComboBox->addItem(tr("Qt Creator"));
applicationComboBox->addItem(tr("Application Example"));
applicationComboBox->addItem(tr("Assistant"));
applicationComboBox->addItem(tr("Designer"));
applicationComboBox->addItem(tr("Linguist"));
applicationComboBox->setEditable(true);
applicationComboBox->setCurrentIndex(3);
applicationComboBox->setCurrentIndex(1);
formatLabel = new QLabel(tr("&Format:"));
formatLabel->setBuddy(formatComboBox);
@ -91,28 +92,30 @@ LocationDialog::LocationDialog(QWidget *parent)
locationsTable->setHorizontalHeaderLabels(labels);
locationsTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
locationsTable->horizontalHeader()->resizeSection(1, 180);
connect(locationsTable, &QTableWidget::itemActivated, this, &LocationDialog::itemActivated);
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
| QDialogButtonBox::Cancel);
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(formatComboBox, SIGNAL(activated(int)),
this, SLOT(updateLocationsTable()));
connect(scopeComboBox, SIGNAL(activated(int)),
this, SLOT(updateLocationsTable()));
typedef void (QComboBox::*QComboIntSignal)(int);
connect(formatComboBox, static_cast<QComboIntSignal>(&QComboBox::activated),
this, &LocationDialog::updateLocationsTable);
connect(scopeComboBox, static_cast<QComboIntSignal>(&QComboBox::activated),
this, &LocationDialog::updateLocationsTable);
connect(organizationComboBox->lineEdit(),
SIGNAL(editingFinished()),
this, SLOT(updateLocationsTable()));
&QLineEdit::editingFinished,
this, &LocationDialog::updateLocationsTable);
connect(applicationComboBox->lineEdit(),
SIGNAL(editingFinished()),
this, SLOT(updateLocationsTable()));
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
&QLineEdit::editingFinished,
this, &LocationDialog::updateLocationsTable);
connect(applicationComboBox, static_cast<QComboIntSignal>(&QComboBox::activated),
this, &LocationDialog::updateLocationsTable);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
QVBoxLayout *locationsLayout = new QVBoxLayout;
QVBoxLayout *locationsLayout = new QVBoxLayout(locationsGroupBox);
locationsLayout->addWidget(locationsTable);
locationsGroupBox->setLayout(locationsLayout);
QGridLayout *mainLayout = new QGridLayout;
QGridLayout *mainLayout = new QGridLayout(this);
mainLayout->addWidget(formatLabel, 0, 0);
mainLayout->addWidget(formatComboBox, 0, 1);
mainLayout->addWidget(scopeLabel, 1, 0);
@ -123,7 +126,6 @@ LocationDialog::LocationDialog(QWidget *parent)
mainLayout->addWidget(applicationComboBox, 3, 1);
mainLayout->addWidget(locationsGroupBox, 4, 0, 1, 2);
mainLayout->addWidget(buttonBox, 5, 0, 1, 2);
setLayout(mainLayout);
updateLocationsTable();
@ -155,11 +157,16 @@ QString LocationDialog::organization() const
QString LocationDialog::application() const
{
if (applicationComboBox->currentText() == tr("Any"))
return "";
return QString();
else
return applicationComboBox->currentText();
}
void LocationDialog::itemActivated(QTableWidgetItem *)
{
buttonBox->button(QDialogButtonBox::Ok)->animateClick();
}
void LocationDialog::updateLocationsTable()
{
locationsTable->setUpdatesEnabled(false);
@ -184,8 +191,7 @@ void LocationDialog::updateLocationsTable()
int row = locationsTable->rowCount();
locationsTable->setRowCount(row + 1);
QTableWidgetItem *item0 = new QTableWidgetItem;
item0->setText(settings.fileName());
QTableWidgetItem *item0 = new QTableWidgetItem(QDir::toNativeSeparators(settings.fileName()));
QTableWidgetItem *item1 = new QTableWidgetItem;
bool disable = (settings.childKeys().isEmpty()

View File

@ -50,6 +50,7 @@ class QDialogButtonBox;
class QGroupBox;
class QLabel;
class QTableWidget;
class QTableWidgetItem;
QT_END_NAMESPACE
class LocationDialog : public QDialog
@ -66,6 +67,7 @@ public:
private slots:
void updateLocationsTable();
void itemActivated(QTableWidgetItem *);
private:
QLabel *formatLabel;

View File

@ -45,6 +45,9 @@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCoreApplication::setApplicationName("Settings Editor");
QCoreApplication::setApplicationVersion(QT_VERSION_STR);
MainWindow mainWin;
mainWin.show();
return app.exec();

View File

@ -45,20 +45,20 @@
#include "settingstree.h"
MainWindow::MainWindow()
: settingsTree(new SettingsTree)
, locationDialog(Q_NULLPTR)
{
settingsTree = new SettingsTree;
setCentralWidget(settingsTree);
locationDialog = 0;
createActions();
createMenus();
autoRefreshAct->setChecked(true);
fallbacksAct->setChecked(true);
setWindowTitle(tr("Settings Editor"));
resize(500, 600);
setWindowTitle(QCoreApplication::applicationName());
const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
adjustSize();
move((availableGeometry.width() - width()) / 2, (availableGeometry.height() - height()) / 2);
}
void MainWindow::openSettings()
@ -66,49 +66,60 @@ void MainWindow::openSettings()
if (!locationDialog)
locationDialog = new LocationDialog(this);
if (locationDialog->exec()) {
QSettings *settings = new QSettings(locationDialog->format(),
locationDialog->scope(),
locationDialog->organization(),
locationDialog->application());
setSettingsObject(settings);
fallbacksAct->setEnabled(true);
}
if (locationDialog->exec() != QDialog::Accepted)
return;
SettingsPtr settings(new QSettings(locationDialog->format(),
locationDialog->scope(),
locationDialog->organization(),
locationDialog->application()));
setSettingsObject(settings);
fallbacksAct->setEnabled(true);
}
void MainWindow::openIniFile()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open INI File"),
"", tr("INI Files (*.ini *.conf)"));
if (!fileName.isEmpty()) {
QSettings *settings = new QSettings(fileName, QSettings::IniFormat);
setSettingsObject(settings);
fallbacksAct->setEnabled(false);
}
const QString directory = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
const QString fileName =
QFileDialog::getOpenFileName(this, tr("Open INI File"),
directory, tr("INI Files (*.ini *.conf)"));
if (fileName.isEmpty())
return;
SettingsPtr settings(new QSettings(fileName, QSettings::IniFormat));
setSettingsObject(settings);
fallbacksAct->setEnabled(false);
}
void MainWindow::openPropertyList()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Property List"),
"", tr("Property List Files (*.plist)"));
if (!fileName.isEmpty()) {
QSettings *settings = new QSettings(fileName, QSettings::NativeFormat);
setSettingsObject(settings);
fallbacksAct->setEnabled(false);
}
const QString directory = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
const QString fileName =
QFileDialog::getOpenFileName(this, tr("Open Property List"),
directory, tr("Property List Files (*.plist)"));
if (fileName.isEmpty())
return;
SettingsPtr settings(new QSettings(fileName, QSettings::NativeFormat));
setSettingsObject(settings);
fallbacksAct->setEnabled(false);
}
void MainWindow::openRegistryPath()
{
QString path = QInputDialog::getText(this, tr("Open Registry Path"),
tr("Enter the path in the Windows registry:"),
QLineEdit::Normal, "HKEY_CURRENT_USER\\");
if (!path.isEmpty()) {
QSettings *settings = new QSettings(path, QSettings::NativeFormat);
setSettingsObject(settings);
fallbacksAct->setEnabled(false);
}
const QString path =
QInputDialog::getText(this, tr("Open Registry Path"),
tr("Enter the path in the Windows registry:"),
QLineEdit::Normal, "HKEY_CURRENT_USER\\");
if (path.isEmpty())
return;
SettingsPtr settings(new QSettings(path, QSettings::NativeFormat));
setSettingsObject(settings);
fallbacksAct->setEnabled(false);
}
void MainWindow::about()
@ -120,88 +131,59 @@ void MainWindow::about()
void MainWindow::createActions()
{
openSettingsAct = new QAction(tr("&Open Application Settings..."), this);
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
QAction *openSettingsAct = fileMenu->addAction(tr("&Open Application Settings..."), this, &MainWindow::openSettings);
openSettingsAct->setShortcuts(QKeySequence::Open);
connect(openSettingsAct, SIGNAL(triggered()), this, SLOT(openSettings()));
openIniFileAct = new QAction(tr("Open I&NI File..."), this);
QAction *openIniFileAct = fileMenu->addAction(tr("Open I&NI File..."), this, &MainWindow::openIniFile);
openIniFileAct->setShortcut(tr("Ctrl+N"));
connect(openIniFileAct, SIGNAL(triggered()), this, SLOT(openIniFile()));
openPropertyListAct = new QAction(tr("Open Mac &Property List..."), this);
#ifdef Q_OS_OSX
QAction *openPropertyListAct = fileMenu->addAction(tr("Open Apple &Property List..."), this, &MainWindow::openPropertyList);
openPropertyListAct->setShortcut(tr("Ctrl+P"));
connect(openPropertyListAct, SIGNAL(triggered()),
this, SLOT(openPropertyList()));
#endif // Q_OS_OSX
openRegistryPathAct = new QAction(tr("Open Windows &Registry Path..."),
this);
#ifdef Q_OS_WIN
QAction *openRegistryPathAct = fileMenu->addAction(tr("Open Windows &Registry Path..."), this, &MainWindow::openRegistryPath);
openRegistryPathAct->setShortcut(tr("Ctrl+G"));
connect(openRegistryPathAct, SIGNAL(triggered()),
this, SLOT(openRegistryPath()));
#endif // Q_OS_WIN
refreshAct = new QAction(tr("&Refresh"), this);
fileMenu->addSeparator();
refreshAct = fileMenu->addAction(tr("&Refresh"), settingsTree, &SettingsTree::refresh);
refreshAct->setShortcut(tr("Ctrl+R"));
refreshAct->setEnabled(false);
connect(refreshAct, SIGNAL(triggered()), settingsTree, SLOT(refresh()));
exitAct = new QAction(tr("E&xit"), this);
fileMenu->addSeparator();
QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close);
exitAct->setShortcuts(QKeySequence::Quit);
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
autoRefreshAct = new QAction(tr("&Auto-Refresh"), this);
QMenu *optionsMenu = menuBar()->addMenu(tr("&Options"));
autoRefreshAct = optionsMenu->addAction(tr("&Auto-Refresh"));
autoRefreshAct->setShortcut(tr("Ctrl+A"));
autoRefreshAct->setCheckable(true);
autoRefreshAct->setEnabled(false);
connect(autoRefreshAct, SIGNAL(triggered(bool)),
settingsTree, SLOT(setAutoRefresh(bool)));
connect(autoRefreshAct, SIGNAL(triggered(bool)),
refreshAct, SLOT(setDisabled(bool)));
connect(autoRefreshAct, &QAction::triggered,
settingsTree, &SettingsTree::setAutoRefresh);
connect(autoRefreshAct, &QAction::triggered,
refreshAct, &QAction::setDisabled);
fallbacksAct = new QAction(tr("&Fallbacks"), this);
fallbacksAct = optionsMenu->addAction(tr("&Fallbacks"));
fallbacksAct->setShortcut(tr("Ctrl+F"));
fallbacksAct->setCheckable(true);
fallbacksAct->setEnabled(false);
connect(fallbacksAct, SIGNAL(triggered(bool)),
settingsTree, SLOT(setFallbacksEnabled(bool)));
connect(fallbacksAct, &QAction::triggered,
settingsTree, &SettingsTree::setFallbacksEnabled);
aboutAct = new QAction(tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
aboutQtAct = new QAction(tr("About &Qt"), this);
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
#ifndef Q_OS_MAC
openPropertyListAct->setEnabled(false);
#endif
#ifndef Q_OS_WIN
openRegistryPathAct->setEnabled(false);
#endif
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(tr("&About"), this, &MainWindow::about);
helpMenu->addAction(tr("About &Qt"), qApp, &QCoreApplication::quit);
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openSettingsAct);
fileMenu->addAction(openIniFileAct);
fileMenu->addAction(openPropertyListAct);
fileMenu->addAction(openRegistryPathAct);
fileMenu->addSeparator();
fileMenu->addAction(refreshAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
optionsMenu = menuBar()->addMenu(tr("&Options"));
optionsMenu->addAction(autoRefreshAct);
optionsMenu->addAction(fallbacksAct);
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
}
void MainWindow::setSettingsObject(QSettings *settings)
void MainWindow::setSettingsObject(const SettingsPtr &settings)
{
settings->setFallbacksEnabled(fallbacksAct->isChecked());
settingsTree->setSettingsObject(settings);
@ -209,14 +191,14 @@ void MainWindow::setSettingsObject(QSettings *settings)
refreshAct->setEnabled(true);
autoRefreshAct->setEnabled(true);
QString niceName = settings->fileName();
niceName.replace("\\", "/");
int pos = niceName.lastIndexOf("/");
QString niceName = QDir::cleanPath(settings->fileName());
int pos = niceName.lastIndexOf(QLatin1Char('/'));
if (pos != -1)
niceName.remove(0, pos + 1);
if (!settings->isWritable())
niceName = tr("%1 (read only)").arg(niceName);
setWindowTitle(tr("%1 - %2").arg(niceName).arg(tr("Settings Editor")));
setWindowTitle(tr("%1 - %2").arg(niceName, QCoreApplication::applicationName()));
statusBar()->showMessage(tr("Opened \"%1\"").arg(QDir::toNativeSeparators(settings->fileName())));
}

View File

@ -42,10 +42,10 @@
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSharedPointer>
QT_BEGIN_NAMESPACE
class QAction;
class QMenu;
class QSettings;
QT_END_NAMESPACE
class LocationDialog;
@ -56,6 +56,8 @@ class MainWindow : public QMainWindow
Q_OBJECT
public:
typedef QSharedPointer<QSettings> SettingsPtr;
MainWindow();
private slots:
@ -67,25 +69,13 @@ private slots:
private:
void createActions();
void createMenus();
void setSettingsObject(QSettings *settings);
void setSettingsObject(const SettingsPtr &settings);
SettingsTree *settingsTree;
LocationDialog *locationDialog;
QMenu *fileMenu;
QMenu *optionsMenu;
QMenu *helpMenu;
QAction *openSettingsAct;
QAction *openIniFileAct;
QAction *openPropertyListAct;
QAction *openRegistryPathAct;
QAction *refreshAct;
QAction *exitAct;
QAction *autoRefreshAct;
QAction *fallbacksAct;
QAction *aboutAct;
QAction *aboutQtAct;
};
#endif

View File

@ -45,18 +45,18 @@
SettingsTree::SettingsTree(QWidget *parent)
: QTreeWidget(parent)
, autoRefresh(false)
{
setItemDelegate(new VariantDelegate(this));
QStringList labels;
labels << tr("Setting") << tr("Type") << tr("Value");
setHeaderLabels(labels);
header()->setSectionResizeMode(0, QHeaderView::Stretch);
header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
header()->setSectionResizeMode(2, QHeaderView::Stretch);
settings = 0;
refreshTimer.setInterval(2000);
autoRefresh = false;
groupIcon.addPixmap(style()->standardPixmap(QStyle::SP_DirClosedIcon),
QIcon::Normal, QIcon::Off);
@ -64,34 +64,37 @@ SettingsTree::SettingsTree(QWidget *parent)
QIcon::Normal, QIcon::On);
keyIcon.addPixmap(style()->standardPixmap(QStyle::SP_FileIcon));
connect(&refreshTimer, SIGNAL(timeout()), this, SLOT(maybeRefresh()));
connect(&refreshTimer, &QTimer::timeout, this, &SettingsTree::maybeRefresh);
}
void SettingsTree::setSettingsObject(QSettings *settings)
SettingsTree::~SettingsTree()
{
delete this->settings;
this->settings = settings;
}
void SettingsTree::setSettingsObject(const SettingsPtr &newSettings)
{
settings = newSettings;
clear();
if (settings) {
settings->setParent(this);
if (settings.isNull()) {
refreshTimer.stop();
} else {
refresh();
if (autoRefresh)
refreshTimer.start();
} else {
refreshTimer.stop();
}
}
QSize SettingsTree::sizeHint() const
{
return QSize(800, 600);
const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
return QSize(availableGeometry.width() * 2 / 3, availableGeometry.height() * 2 / 3);
}
void SettingsTree::setAutoRefresh(bool autoRefresh)
{
this->autoRefresh = autoRefresh;
if (settings) {
if (!settings.isNull()) {
if (autoRefresh) {
maybeRefresh();
refreshTimer.start();
@ -103,7 +106,7 @@ void SettingsTree::setAutoRefresh(bool autoRefresh)
void SettingsTree::setFallbacksEnabled(bool enabled)
{
if (settings) {
if (!settings.isNull()) {
settings->setFallbacksEnabled(enabled);
refresh();
}
@ -117,17 +120,17 @@ void SettingsTree::maybeRefresh()
void SettingsTree::refresh()
{
if (!settings)
if (settings.isNull())
return;
disconnect(this, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this, SLOT(updateSetting(QTreeWidgetItem*)));
disconnect(this, &QTreeWidget::itemChanged,
this, &SettingsTree::updateSetting);
settings->sync();
updateChildItems(0);
connect(this, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this, SLOT(updateSetting(QTreeWidgetItem*)));
connect(this, &QTreeWidget::itemChanged,
this, &SettingsTree::updateSetting);
}
bool SettingsTree::event(QEvent *event)
@ -144,7 +147,7 @@ void SettingsTree::updateSetting(QTreeWidgetItem *item)
QString key = item->text(0);
QTreeWidgetItem *ancestor = item->parent();
while (ancestor) {
key.prepend(ancestor->text(0) + "/");
key.prepend(ancestor->text(0) + QLatin1Char('/'));
ancestor = ancestor->parent();
}
@ -162,8 +165,8 @@ void SettingsTree::updateChildItems(QTreeWidgetItem *parent)
int childIndex = findChild(parent, group, dividerIndex);
if (childIndex != -1) {
child = childAt(parent, childIndex);
child->setText(1, "");
child->setText(2, "");
child->setText(1, QString());
child->setText(2, QString());
child->setData(2, Qt::UserRole, QVariant());
moveItemForward(parent, childIndex, dividerIndex);
} else {
@ -177,7 +180,7 @@ void SettingsTree::updateChildItems(QTreeWidgetItem *parent)
settings->endGroup();
}
foreach (QString key, settings->childKeys()) {
foreach (const QString &key, settings->childKeys()) {
QTreeWidgetItem *child;
int childIndex = findChild(parent, key, 0);

View File

@ -44,6 +44,7 @@
#include <QIcon>
#include <QTimer>
#include <QTreeWidget>
#include <QSharedPointer>
QT_BEGIN_NAMESPACE
class QSettings;
@ -54,9 +55,12 @@ class SettingsTree : public QTreeWidget
Q_OBJECT
public:
SettingsTree(QWidget *parent = 0);
typedef QSharedPointer<QSettings> SettingsPtr;
void setSettingsObject(QSettings *settings);
SettingsTree(QWidget *parent = 0);
~SettingsTree();
void setSettingsObject(const SettingsPtr &settings);
QSize sizeHint() const Q_DECL_OVERRIDE;
public slots:
@ -80,7 +84,7 @@ private:
int findChild(QTreeWidgetItem *parent, const QString &text, int startIndex);
void moveItemForward(QTreeWidgetItem *parent, int oldIndex, int newIndex);
QSettings *settings;
SettingsPtr settings;
QTimer refreshTimer;
bool autoRefresh;
QIcon groupIcon;

View File

@ -46,33 +46,95 @@
IconPreviewArea::IconPreviewArea(QWidget *parent)
: QWidget(parent)
{
QGridLayout *mainLayout = new QGridLayout;
setLayout(mainLayout);
QGridLayout *mainLayout = new QGridLayout(this);
stateLabels[0] = createHeaderLabel(tr("Off"));
stateLabels[1] = createHeaderLabel(tr("On"));
for (int row = 0; row < NumStates; ++row) {
stateLabels[row] = createHeaderLabel(IconPreviewArea::iconStateNames().at(row));
mainLayout->addWidget(stateLabels[row], row + 1, 0);
}
Q_ASSERT(NumStates == 2);
modeLabels[0] = createHeaderLabel(tr("Normal"));
modeLabels[1] = createHeaderLabel(tr("Active"));
modeLabels[2] = createHeaderLabel(tr("Disabled"));
modeLabels[3] = createHeaderLabel(tr("Selected"));
for (int column = 0; column < NumModes; ++column) {
modeLabels[column] = createHeaderLabel(IconPreviewArea::iconModeNames().at(column));
mainLayout->addWidget(modeLabels[column], 0, column + 1);
}
Q_ASSERT(NumModes == 4);
for (int j = 0; j < NumStates; ++j)
mainLayout->addWidget(stateLabels[j], j + 1, 0);
for (int i = 0; i < NumModes; ++i) {
mainLayout->addWidget(modeLabels[i], 0, i + 1);
for (int j = 0; j < NumStates; ++j) {
pixmapLabels[i][j] = createPixmapLabel();
mainLayout->addWidget(pixmapLabels[i][j], j + 1, i + 1);
for (int column = 0; column < NumModes; ++column) {
for (int row = 0; row < NumStates; ++row) {
pixmapLabels[column][row] = createPixmapLabel();
mainLayout->addWidget(pixmapLabels[column][row], row + 1, column + 1);
}
}
}
//! [0]
#ifdef Q_COMPILER_INITIALIZER_LISTS
//! [42]
QVector<QIcon::Mode> IconPreviewArea::iconModes()
{
static const QVector<QIcon::Mode> result = {QIcon::Normal, QIcon::Active, QIcon::Disabled, QIcon::Selected};
return result;
}
QVector<QIcon::State> IconPreviewArea::iconStates()
{
static const QVector<QIcon::State> result = {QIcon::Off, QIcon::On};
return result;
}
QStringList IconPreviewArea::iconModeNames()
{
static const QStringList result = {tr("Normal"), tr("Active"), tr("Disabled"), tr("Selected")};
return result;
}
QStringList IconPreviewArea::iconStateNames()
{
static const QStringList result = {tr("Off"), tr("On")};
return result;
}
//! [42]
#else // Q_COMPILER_INITIALIZER_LISTS
//! [43]
QVector<QIcon::Mode> IconPreviewArea::iconModes()
{
static QVector<QIcon::Mode> result;
if (result.isEmpty())
result << QIcon::Normal << QIcon::Active << QIcon::Disabled << QIcon::Selected;
return result;
}
//! [43]
QVector<QIcon::State> IconPreviewArea::iconStates()
{
static QVector<QIcon::State> result;
if (result.isEmpty())
result << QIcon::Off << QIcon::On;
return result;
}
QStringList IconPreviewArea::iconModeNames()
{
static QStringList result;
if (result.isEmpty())
result << tr("Normal") << tr("Active") << tr("Disabled") << tr("Selected");
return result;
}
QStringList IconPreviewArea::iconStateNames()
{
static QStringList result;
if (result.isEmpty())
result << tr("Off") << tr("On");
return result;
}
#endif // !Q_COMPILER_INITIALIZER_LISTS
//! [1]
void IconPreviewArea::setIcon(const QIcon &icon)
{
@ -118,23 +180,27 @@ QLabel *IconPreviewArea::createPixmapLabel()
//! [5]
void IconPreviewArea::updatePixmapLabels()
{
for (int i = 0; i < NumModes; ++i) {
QIcon::Mode mode;
if (i == 0) {
mode = QIcon::Normal;
} else if (i == 1) {
mode = QIcon::Active;
} else if (i == 2) {
mode = QIcon::Disabled;
} else {
mode = QIcon::Selected;
}
for (int j = 0; j < NumStates; ++j) {
QIcon::State state = (j == 0) ? QIcon::Off : QIcon::On;
QPixmap pixmap = icon.pixmap(size, mode, state);
pixmapLabels[i][j]->setPixmap(pixmap);
pixmapLabels[i][j]->setEnabled(!pixmap.isNull());
QWindow *window = Q_NULLPTR;
if (const QWidget *nativeParent = nativeParentWidget())
window = nativeParent->windowHandle();
for (int column = 0; column < NumModes; ++column) {
for (int row = 0; row < NumStates; ++row) {
const QPixmap pixmap =
icon.pixmap(window, size, IconPreviewArea::iconModes().at(column),
IconPreviewArea::iconStates().at(row));
QLabel *pixmapLabel = pixmapLabels[column][row];
pixmapLabel->setPixmap(pixmap);
pixmapLabel->setEnabled(!pixmap.isNull());
QString toolTip;
if (!pixmap.isNull()) {
const QSize actualSize = icon.actualSize(size);
toolTip =
tr("Size: %1x%2\nActual size: %3x%4\nDevice pixel ratio: %5")
.arg(size.width()).arg(size.height())
.arg(actualSize.width()).arg(actualSize.height())
.arg(pixmap.devicePixelRatioF());
}
pixmapLabel->setToolTip(toolTip);
}
}
}

View File

@ -43,6 +43,8 @@
#include <QIcon>
#include <QWidget>
#include <QStringList>
#include <QVector>
QT_BEGIN_NAMESPACE
class QLabel;
@ -54,11 +56,16 @@ class IconPreviewArea : public QWidget
Q_OBJECT
public:
IconPreviewArea(QWidget *parent = 0);
explicit IconPreviewArea(QWidget *parent = Q_NULLPTR);
void setIcon(const QIcon &icon);
void setSize(const QSize &size);
static QVector<QIcon::Mode> iconModes();
static QVector<QIcon::State> iconStates();
static QStringList iconModeNames();
static QStringList iconStateNames();
private:
QLabel *createHeaderLabel(const QString &text);
QLabel *createPixmapLabel();

View File

@ -10,6 +10,8 @@ SOURCES = iconpreviewarea.cpp \
main.cpp \
mainwindow.cpp
DEFINES += SRCDIR=\\\"$$PWD/\\\"
EXAMPLE_FILES = images/*
# install

View File

@ -52,13 +52,13 @@ IconSizeSpinBox::IconSizeSpinBox(QWidget *parent)
//! [1]
int IconSizeSpinBox::valueFromText(const QString &text) const
{
QRegExp regExp(tr("(\\d+)(\\s*[xx]\\s*\\d+)?"));
static const QRegularExpression regExp(tr("(\\d+)(\\s*[xx]\\s*\\d+)?"));
Q_ASSERT(regExp.isValid());
if (regExp.exactMatch(text)) {
return regExp.cap(1).toInt();
} else {
return 0;
}
const QRegularExpressionMatch match = regExp.match(text);
if (match.isValid())
return match.captured(1).toInt();
return 0;
}
//! [1]

View File

@ -49,7 +49,7 @@ class IconSizeSpinBox : public QSpinBox
Q_OBJECT
public:
IconSizeSpinBox(QWidget *parent = 0);
explicit IconSizeSpinBox(QWidget *parent = Q_NULLPTR);
int valueFromText(const QString &text) const Q_DECL_OVERRIDE;
QString textFromValue(int value) const Q_DECL_OVERRIDE;

View File

@ -41,6 +41,7 @@
#include <QtWidgets>
#include "imagedelegate.h"
#include "iconpreviewarea.h"
//! [0]
ImageDelegate::ImageDelegate(QObject *parent)
@ -55,17 +56,14 @@ QWidget *ImageDelegate::createEditor(QWidget *parent,
const QModelIndex &index) const
{
QComboBox *comboBox = new QComboBox(parent);
if (index.column() == 1) {
comboBox->addItem(tr("Normal"));
comboBox->addItem(tr("Active"));
comboBox->addItem(tr("Disabled"));
comboBox->addItem(tr("Selected"));
} else if (index.column() == 2) {
comboBox->addItem(tr("Off"));
comboBox->addItem(tr("On"));
}
if (index.column() == 1)
comboBox->addItems(IconPreviewArea::iconModeNames());
else if (index.column() == 2)
comboBox->addItems(IconPreviewArea::iconStateNames());
connect(comboBox, SIGNAL(activated(int)), this, SLOT(emitCommitData()));
typedef void (QComboBox::*QComboBoxIntSignal)(int);
connect(comboBox, static_cast<QComboBoxIntSignal>(&QComboBox::activated),
this, &ImageDelegate::emitCommitData);
return comboBox;
}

View File

@ -49,7 +49,7 @@ class ImageDelegate : public QItemDelegate
Q_OBJECT
public:
ImageDelegate(QObject *parent = 0);
explicit ImageDelegate(QObject *parent = Q_NULLPTR);
//! [0]
//! [1]

View File

@ -39,13 +39,39 @@
****************************************************************************/
#include <QApplication>
#include <QCommandLineParser>
#include <QDesktopWidget>
#include "mainwindow.h"
//! [45]
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCoreApplication::setApplicationName(MainWindow::tr("Icons"));
QCoreApplication::setApplicationVersion(QT_VERSION_STR);
QCommandLineParser commandLineParser;
commandLineParser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
commandLineParser.addHelpOption();
commandLineParser.addVersionOption();
QCommandLineOption noHighDpiPixmapOption("no-highdpi-pixmaps",
"Disable High DPI image loading (Qt::AA_UseHighDpiPixmaps)");
commandLineParser.addOption(noHighDpiPixmapOption);
commandLineParser.addPositionalArgument(MainWindow::tr("[file]"), MainWindow::tr("Icon file(s) to open."));
commandLineParser.process(QCoreApplication::arguments());
if (!commandLineParser.isSet(noHighDpiPixmapOption))
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
MainWindow mainWin;
if (!commandLineParser.positionalArguments().isEmpty())
mainWin.loadImages(commandLineParser.positionalArguments());
const QRect availableGeometry = QApplication::desktop()->availableGeometry(&mainWin);
mainWin.resize(availableGeometry.width() / 2, availableGeometry.height() * 2 / 3);
mainWin.move((availableGeometry.width() - mainWin.width()) / 2, (availableGeometry.height() - mainWin.height()) / 2);
mainWin.show();
return app.exec();
}
//! [45]

View File

@ -45,34 +45,49 @@
#include "imagedelegate.h"
#include "mainwindow.h"
//! [40]
enum { OtherSize = QStyle::PM_CustomBase };
//! [40]
//! [0]
MainWindow::MainWindow()
{
centralWidget = new QWidget;
QWidget *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
createPreviewGroupBox();
createImagesGroupBox();
createIconSizeGroupBox();
createActions();
createMenus();
createContextMenu();
QGridLayout *mainLayout = new QGridLayout;
QGridLayout *mainLayout = new QGridLayout(centralWidget);
QGroupBox *previewGroupBox = new QGroupBox(tr("Preview"));
previewArea = new IconPreviewArea(previewGroupBox);
QVBoxLayout *previewLayout = new QVBoxLayout(previewGroupBox);
previewLayout->addWidget(previewArea);
mainLayout->addWidget(previewGroupBox, 0, 0, 1, 2);
mainLayout->addWidget(imagesGroupBox, 1, 0);
mainLayout->addWidget(iconSizeGroupBox, 1, 1);
centralWidget->setLayout(mainLayout);
mainLayout->addWidget(createImagesGroupBox(), 1, 0);
QVBoxLayout *vBox = new QVBoxLayout;
vBox->addWidget(createIconSizeGroupBox());
vBox->addWidget(createHighDpiIconSizeGroupBox());
vBox->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
mainLayout->addLayout(vBox, 1, 1);
createContextMenu();
setWindowTitle(tr("Icons"));
checkCurrentStyle();
otherRadioButton->click();
resize(minimumSizeHint());
sizeButtonGroup->button(OtherSize)->click();
}
//! [0]
//! [44]
void MainWindow::show()
{
QMainWindow::show();
connect(windowHandle(), &QWindow::screenChanged, this, &MainWindow::screenChanged);
screenChanged();
}
//! [44]
//! [1]
void MainWindow::about()
{
@ -89,60 +104,62 @@ void MainWindow::changeStyle(bool checked)
if (!checked)
return;
QAction *action = qobject_cast<QAction *>(sender());
const QAction *action = qobject_cast<QAction *>(sender());
//! [2] //! [3]
QStyle *style = QStyleFactory::create(action->data().toString());
//! [3] //! [4]
Q_ASSERT(style);
QApplication::setStyle(style);
smallRadioButton->setText(tr("Small (%1 x %1)")
.arg(style->pixelMetric(QStyle::PM_SmallIconSize)));
largeRadioButton->setText(tr("Large (%1 x %1)")
.arg(style->pixelMetric(QStyle::PM_LargeIconSize)));
toolBarRadioButton->setText(tr("Toolbars (%1 x %1)")
.arg(style->pixelMetric(QStyle::PM_ToolBarIconSize)));
listViewRadioButton->setText(tr("List views (%1 x %1)")
.arg(style->pixelMetric(QStyle::PM_ListViewIconSize)));
iconViewRadioButton->setText(tr("Icon views (%1 x %1)")
.arg(style->pixelMetric(QStyle::PM_IconViewIconSize)));
tabBarRadioButton->setText(tr("Tab bars (%1 x %1)")
.arg(style->pixelMetric(QStyle::PM_TabBarIconSize)));
foreach (QAbstractButton *button, sizeButtonGroup->buttons()) {
const QStyle::PixelMetric metric = static_cast<QStyle::PixelMetric>(sizeButtonGroup->id(button));
const int value = style->pixelMetric(metric);
switch (metric) {
case QStyle::PM_SmallIconSize:
button->setText(tr("Small (%1 x %1)").arg(value));
break;
case QStyle::PM_LargeIconSize:
button->setText(tr("Large (%1 x %1)").arg(value));
break;
case QStyle::PM_ToolBarIconSize:
button->setText(tr("Toolbars (%1 x %1)").arg(value));
break;
case QStyle::PM_ListViewIconSize:
button->setText(tr("List views (%1 x %1)").arg(value));
break;
case QStyle::PM_IconViewIconSize:
button->setText(tr("Icon views (%1 x %1)").arg(value));
break;
case QStyle::PM_TabBarIconSize:
button->setText(tr("Tab bars (%1 x %1)").arg(value));
break;
default:
break;
}
}
changeSize();
triggerChangeSize();
}
//! [4]
//! [5]
void MainWindow::changeSize(bool checked)
void MainWindow::changeSize(int id, bool checked)
{
if (!checked)
return;
int extent;
const bool other = id == int(OtherSize);
const int extent = other
? otherSpinBox->value()
: QApplication::style()->pixelMetric(static_cast<QStyle::PixelMetric>(id));
if (otherRadioButton->isChecked()) {
extent = otherSpinBox->value();
} else {
QStyle::PixelMetric metric;
if (smallRadioButton->isChecked()) {
metric = QStyle::PM_SmallIconSize;
} else if (largeRadioButton->isChecked()) {
metric = QStyle::PM_LargeIconSize;
} else if (toolBarRadioButton->isChecked()) {
metric = QStyle::PM_ToolBarIconSize;
} else if (listViewRadioButton->isChecked()) {
metric = QStyle::PM_ListViewIconSize;
} else if (iconViewRadioButton->isChecked()) {
metric = QStyle::PM_IconViewIconSize;
} else {
metric = QStyle::PM_TabBarIconSize;
}
extent = QApplication::style()->pixelMetric(metric);
}
previewArea->setSize(QSize(extent, extent));
otherSpinBox->setEnabled(otherRadioButton->isChecked());
otherSpinBox->setEnabled(other);
}
void MainWindow::triggerChangeSize()
{
changeSize(sizeButtonGroup->checkedId(), true);
}
//! [5]
@ -152,33 +169,21 @@ void MainWindow::changeIcon()
QIcon icon;
for (int row = 0; row < imagesTable->rowCount(); ++row) {
QTableWidgetItem *item0 = imagesTable->item(row, 0);
QTableWidgetItem *item1 = imagesTable->item(row, 1);
QTableWidgetItem *item2 = imagesTable->item(row, 2);
const QTableWidgetItem *fileItem = imagesTable->item(row, 0);
const QTableWidgetItem *modeItem = imagesTable->item(row, 1);
const QTableWidgetItem *stateItem = imagesTable->item(row, 2);
if (item0->checkState() == Qt::Checked) {
QIcon::Mode mode;
if (item1->text() == tr("Normal")) {
mode = QIcon::Normal;
} else if (item1->text() == tr("Active")) {
mode = QIcon::Active;
} else if (item1->text() == tr("Disabled")) {
mode = QIcon::Disabled;
} else {
mode = QIcon::Selected;
}
QIcon::State state;
if (item2->text() == tr("On")) {
state = QIcon::On;
} else {
state = QIcon::Off;
//! [6] //! [7]
}
//! [7]
if (fileItem->checkState() == Qt::Checked) {
const int modeIndex = IconPreviewArea::iconModeNames().indexOf(modeItem->text());
Q_ASSERT(modeIndex >= 0);
const int stateIndex = IconPreviewArea::iconStateNames().indexOf(stateItem->text());
Q_ASSERT(stateIndex >= 0);
const QIcon::Mode mode = IconPreviewArea::iconModes().at(modeIndex);
const QIcon::State state = IconPreviewArea::iconStates().at(stateIndex);
//! [6]
//! [8]
QString fileName = item0->data(Qt::UserRole).toString();
const QString fileName = fileItem->data(Qt::UserRole).toString();
QImage image(fileName);
if (!image.isNull())
icon.addPixmap(QPixmap::fromImage(image), mode, state);
@ -193,61 +198,109 @@ void MainWindow::changeIcon()
}
//! [11]
//! [12]
void MainWindow::addImages()
void MainWindow::addSampleImages()
{
QStringList fileNames = QFileDialog::getOpenFileNames(this,
tr("Open Images"), "",
tr("Images (*.png *.xpm *.jpg);;"
"All Files (*)"));
if (!fileNames.isEmpty()) {
foreach (QString fileName, fileNames) {
int row = imagesTable->rowCount();
imagesTable->setRowCount(row + 1);
//! [12]
addImages(QLatin1String(SRCDIR) + QLatin1String("/images"));
}
void MainWindow::addOtherImages()
{
static bool firstInvocation = true;
QString directory;
if (firstInvocation) {
firstInvocation = false;
directory = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).value(0, QString());
}
addImages(directory);
}
//! [12]
void MainWindow::addImages(const QString &directory)
{
QFileDialog fileDialog(this, tr("Open Images"), directory);
QStringList mimeTypeFilters;
foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes())
mimeTypeFilters.append(mimeTypeName);
mimeTypeFilters.sort();
fileDialog.setMimeTypeFilters(mimeTypeFilters);
fileDialog.selectMimeTypeFilter(QLatin1String("image/png"));
fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
fileDialog.setFileMode(QFileDialog::ExistingFiles);
if (!nativeFileDialogAct->isChecked())
fileDialog.setOption(QFileDialog::DontUseNativeDialog);
if (fileDialog.exec() == QDialog::Accepted)
loadImages(fileDialog.selectedFiles());
//! [12]
}
void MainWindow::loadImages(const QStringList &fileNames)
{
foreach (const QString &fileName, fileNames) {
const int row = imagesTable->rowCount();
imagesTable->setRowCount(row + 1);
//! [13]
QString imageName = QFileInfo(fileName).baseName();
const QFileInfo fileInfo(fileName);
const QString imageName = fileInfo.baseName();
const QString fileName2x = fileInfo.absolutePath()
+ QLatin1Char('/') + imageName + QLatin1String("@2x.") + fileInfo.suffix();
const QFileInfo fileInfo2x(fileName2x);
const QImage image(fileName);
const QString toolTip =
tr("Directory: %1\nFile: %2\nFile@2x: %3\nSize: %4x%5")
.arg(QDir::toNativeSeparators(fileInfo.absolutePath()), fileInfo.fileName())
.arg(fileInfo2x.exists() ? fileInfo2x.fileName() : tr("<None>"))
.arg(image.width()).arg(image.height());
//! [13] //! [14]
QTableWidgetItem *item0 = new QTableWidgetItem(imageName);
item0->setData(Qt::UserRole, fileName);
item0->setFlags(item0->flags() & ~Qt::ItemIsEditable);
QTableWidgetItem *fileItem = new QTableWidgetItem(imageName);
fileItem->setData(Qt::UserRole, fileName);
fileItem->setIcon(QPixmap::fromImage(image));
fileItem->setFlags((fileItem->flags() | Qt::ItemIsUserCheckable) & ~Qt::ItemIsEditable);
fileItem->setToolTip(toolTip);
//! [14]
//! [15]
QTableWidgetItem *item1 = new QTableWidgetItem(tr("Normal"));
QIcon::Mode mode = QIcon::Normal;
//! [15] //! [16]
QTableWidgetItem *item2 = new QTableWidgetItem(tr("Off"));
QIcon::State state = QIcon::Off;
if (guessModeStateAct->isChecked()) {
if (imageName.contains(QLatin1String("_act"), Qt::CaseInsensitive))
mode = QIcon::Active;
else if (imageName.contains(QLatin1String("_dis"), Qt::CaseInsensitive))
mode = QIcon::Disabled;
else if (imageName.contains(QLatin1String("_sel"), Qt::CaseInsensitive))
mode = QIcon::Selected;
if (guessModeStateAct->isChecked()) {
if (fileName.contains("_act")) {
item1->setText(tr("Active"));
} else if (fileName.contains("_dis")) {
item1->setText(tr("Disabled"));
} else if (fileName.contains("_sel")) {
item1->setText(tr("Selected"));
}
if (fileName.contains("_on"))
item2->setText(tr("On"));
if (imageName.contains(QLatin1String("_on"), Qt::CaseInsensitive))
state = QIcon::On;
//! [16] //! [17]
}
}
//! [17]
//! [18]
imagesTable->setItem(row, 0, item0);
imagesTable->setItem(row, 0, fileItem);
//! [18] //! [19]
imagesTable->setItem(row, 1, item1);
imagesTable->setItem(row, 2, item2);
imagesTable->openPersistentEditor(item1);
imagesTable->openPersistentEditor(item2);
QTableWidgetItem *modeItem =
new QTableWidgetItem(IconPreviewArea::iconModeNames().at(IconPreviewArea::iconModes().indexOf(mode)));
modeItem->setToolTip(toolTip);
imagesTable->setItem(row, 1, modeItem);
QTableWidgetItem *stateItem =
new QTableWidgetItem(IconPreviewArea::iconStateNames().at(IconPreviewArea::iconStates().indexOf(state)));
stateItem->setToolTip(toolTip);
imagesTable->setItem(row, 2, stateItem);
imagesTable->openPersistentEditor(modeItem);
imagesTable->openPersistentEditor(stateItem);
item0->setCheckState(Qt::Checked);
}
fileItem->setCheckState(Qt::Checked);
}
}
//! [19]
void MainWindow::useHighDpiPixmapsChanged(int checkState)
{
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, checkState == Qt::Checked);
changeIcon();
}
//! [20]
void MainWindow::removeAllImages()
{
@ -256,21 +309,10 @@ void MainWindow::removeAllImages()
}
//! [20]
void MainWindow::createPreviewGroupBox()
{
previewGroupBox = new QGroupBox(tr("Preview"));
previewArea = new IconPreviewArea;
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(previewArea);
previewGroupBox->setLayout(layout);
}
//! [21]
void MainWindow::createImagesGroupBox()
QWidget *MainWindow::createImagesGroupBox()
{
imagesGroupBox = new QGroupBox(tr("Images"));
QGroupBox *imagesGroupBox = new QGroupBox(tr("Images"));
imagesTable = new QTableWidget;
imagesTable->setSelectionMode(QAbstractItemView::NoSelection);
@ -292,57 +334,63 @@ void MainWindow::createImagesGroupBox()
//! [23]
//! [24]
connect(imagesTable, SIGNAL(itemChanged(QTableWidgetItem*)),
connect(imagesTable, &QTableWidget::itemChanged,
//! [24] //! [25]
this, SLOT(changeIcon()));
this, &MainWindow::changeIcon);
QVBoxLayout *layout = new QVBoxLayout;
QVBoxLayout *layout = new QVBoxLayout(imagesGroupBox);
layout->addWidget(imagesTable);
imagesGroupBox->setLayout(layout);
return imagesGroupBox;
}
//! [25]
//! [26]
void MainWindow::createIconSizeGroupBox()
QWidget *MainWindow::createIconSizeGroupBox()
{
iconSizeGroupBox = new QGroupBox(tr("Icon Size"));
QGroupBox *iconSizeGroupBox = new QGroupBox(tr("Icon Size"));
smallRadioButton = new QRadioButton;
largeRadioButton = new QRadioButton;
toolBarRadioButton = new QRadioButton;
listViewRadioButton = new QRadioButton;
iconViewRadioButton = new QRadioButton;
tabBarRadioButton = new QRadioButton;
otherRadioButton = new QRadioButton(tr("Other:"));
sizeButtonGroup = new QButtonGroup(this);
sizeButtonGroup->setExclusive(true);
typedef void (QButtonGroup::*QButtonGroupIntBoolSignal)(int, bool);
connect(sizeButtonGroup, static_cast<QButtonGroupIntBoolSignal>(&QButtonGroup::buttonToggled),
this, &MainWindow::changeSize);
QRadioButton *smallRadioButton = new QRadioButton;
sizeButtonGroup->addButton(smallRadioButton, QStyle::PM_SmallIconSize);
QRadioButton *largeRadioButton = new QRadioButton;
sizeButtonGroup->addButton(largeRadioButton, QStyle::PM_LargeIconSize);
QRadioButton *toolBarRadioButton = new QRadioButton;
sizeButtonGroup->addButton(toolBarRadioButton, QStyle::PM_ToolBarIconSize);
QRadioButton *listViewRadioButton = new QRadioButton;
sizeButtonGroup->addButton(listViewRadioButton, QStyle::PM_ListViewIconSize);
QRadioButton *iconViewRadioButton = new QRadioButton;
sizeButtonGroup->addButton(iconViewRadioButton, QStyle::PM_IconViewIconSize);
QRadioButton *tabBarRadioButton = new QRadioButton;
sizeButtonGroup->addButton(tabBarRadioButton, QStyle::PM_TabBarIconSize);
QRadioButton *otherRadioButton = new QRadioButton(tr("Other:"));
sizeButtonGroup->addButton(otherRadioButton, OtherSize);
otherSpinBox = new IconSizeSpinBox;
otherSpinBox->setRange(8, 128);
otherSpinBox->setRange(8, 256);
const QString spinBoxToolTip =
tr("Enter a custom size within %1..%2")
.arg(otherSpinBox->minimum()).arg(otherSpinBox->maximum());
otherSpinBox->setValue(64);
otherSpinBox->setToolTip(spinBoxToolTip);
otherRadioButton->setToolTip(spinBoxToolTip);
//! [26]
//! [27]
connect(smallRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(largeRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(toolBarRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(listViewRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(iconViewRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(tabBarRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(otherRadioButton, SIGNAL(toggled(bool)),
this, SLOT(changeSize(bool)));
connect(otherSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeSize()));
typedef void (QSpinBox::*QSpinBoxIntSignal)(int);
connect(otherSpinBox, static_cast<QSpinBoxIntSignal>(&QSpinBox::valueChanged),
this, &MainWindow::triggerChangeSize);
QHBoxLayout *otherSizeLayout = new QHBoxLayout;
otherSizeLayout->addWidget(otherRadioButton);
otherSizeLayout->addWidget(otherSpinBox);
otherSizeLayout->addStretch();
QGridLayout *layout = new QGridLayout;
QGridLayout *layout = new QGridLayout(iconSizeGroupBox);
layout->addWidget(smallRadioButton, 0, 0);
layout->addWidget(largeRadioButton, 1, 0);
layout->addWidget(toolBarRadioButton, 2, 0);
@ -351,75 +399,99 @@ void MainWindow::createIconSizeGroupBox()
layout->addWidget(tabBarRadioButton, 2, 1);
layout->addLayout(otherSizeLayout, 3, 0, 1, 2);
layout->setRowStretch(4, 1);
iconSizeGroupBox->setLayout(layout);
return iconSizeGroupBox;
}
//! [27]
void MainWindow::screenChanged()
{
devicePixelRatioLabel->setText(QString::number(devicePixelRatioF()));
if (const QWindow *window = windowHandle()) {
const QScreen *screen = window->screen();
const QString screenDescription =
tr("\"%1\" (%2x%3)").arg(screen->name())
.arg(screen->geometry().width()).arg(screen->geometry().height());
screenNameLabel->setText(screenDescription);
}
changeIcon();
}
QWidget *MainWindow::createHighDpiIconSizeGroupBox()
{
QGroupBox *highDpiGroupBox = new QGroupBox(tr("High DPI Scaling"));
QFormLayout *layout = new QFormLayout(highDpiGroupBox);
devicePixelRatioLabel = new QLabel(highDpiGroupBox);
screenNameLabel = new QLabel(highDpiGroupBox);
layout->addRow(tr("Screen:"), screenNameLabel);
layout->addRow(tr("Device pixel ratio:"), devicePixelRatioLabel);
QCheckBox *highDpiPixmapsCheckBox = new QCheckBox(QLatin1String("Qt::AA_UseHighDpiPixmaps"));
highDpiPixmapsCheckBox->setChecked(QCoreApplication::testAttribute(Qt::AA_UseHighDpiPixmaps));
connect(highDpiPixmapsCheckBox, &QCheckBox::stateChanged, this, &MainWindow::useHighDpiPixmapsChanged);
layout->addRow(highDpiPixmapsCheckBox);
return highDpiGroupBox;
}
//! [28]
void MainWindow::createActions()
{
addImagesAct = new QAction(tr("&Add Images..."), this);
addImagesAct->setShortcut(tr("Ctrl+A"));
connect(addImagesAct, SIGNAL(triggered()), this, SLOT(addImages()));
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
addSampleImagesAct = new QAction(tr("Add &Sample Images..."), this);
addSampleImagesAct->setShortcut(tr("Ctrl+A"));
connect(addSampleImagesAct, &QAction::triggered, this, &MainWindow::addSampleImages);
fileMenu->addAction(addSampleImagesAct);
addOtherImagesAct = new QAction(tr("&Add Images..."), this);
addOtherImagesAct->setShortcut(QKeySequence::Open);
connect(addOtherImagesAct, &QAction::triggered, this, &MainWindow::addOtherImages);
fileMenu->addAction(addOtherImagesAct);
removeAllImagesAct = new QAction(tr("&Remove All Images"), this);
removeAllImagesAct->setShortcut(tr("Ctrl+R"));
connect(removeAllImagesAct, SIGNAL(triggered()),
this, SLOT(removeAllImages()));
connect(removeAllImagesAct, &QAction::triggered,
this, &MainWindow::removeAllImages);
fileMenu->addAction(removeAllImagesAct);
exitAct = new QAction(tr("&Quit"), this);
fileMenu->addSeparator();
QAction *exitAct = fileMenu->addAction(tr("&Quit"), this, &QWidget::close);
exitAct->setShortcuts(QKeySequence::Quit);
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
styleActionGroup = new QActionGroup(this);
foreach (QString styleName, QStyleFactory::keys()) {
QAction *action = new QAction(styleActionGroup);
action->setText(tr("%1 Style").arg(styleName));
foreach (const QString &styleName, QStyleFactory::keys()) {
QAction *action = new QAction(tr("%1 Style").arg(styleName), styleActionGroup);
action->setData(styleName);
action->setCheckable(true);
connect(action, SIGNAL(triggered(bool)), this, SLOT(changeStyle(bool)));
connect(action, &QAction::triggered, this, &MainWindow::changeStyle);
viewMenu->addAction(action);
}
QMenu *settingsMenu = menuBar()->addMenu(tr("&Settings"));
guessModeStateAct = new QAction(tr("&Guess Image Mode/State"), this);
guessModeStateAct->setCheckable(true);
guessModeStateAct->setChecked(true);
settingsMenu->addAction(guessModeStateAct);
aboutAct = new QAction(tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
nativeFileDialogAct = new QAction(tr("&Use Native File Dialog"), this);
nativeFileDialogAct->setCheckable(true);
nativeFileDialogAct->setChecked(true);
settingsMenu->addAction(nativeFileDialogAct);
aboutQtAct = new QAction(tr("About &Qt"), this);
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(tr("&About"), this, &MainWindow::about);
helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
}
//! [28]
//! [29]
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(addImagesAct);
fileMenu->addAction(removeAllImagesAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
viewMenu = menuBar()->addMenu(tr("&View"));
foreach (QAction *action, styleActionGroup->actions())
viewMenu->addAction(action);
viewMenu->addSeparator();
viewMenu->addAction(guessModeStateAct);
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
}
//! [29]
//! [30]
void MainWindow::createContextMenu()
{
imagesTable->setContextMenuPolicy(Qt::ActionsContextMenu);
imagesTable->addAction(addImagesAct);
imagesTable->addAction(addSampleImagesAct);
imagesTable->addAction(addOtherImagesAct);
imagesTable->addAction(removeAllImagesAct);
}
//! [30]
@ -429,14 +501,13 @@ void MainWindow::checkCurrentStyle()
{
foreach (QAction *action, styleActionGroup->actions()) {
QString styleName = action->data().toString();
QStyle *candidate = QStyleFactory::create(styleName);
Q_ASSERT(candidate);
QScopedPointer<QStyle> candidate(QStyleFactory::create(styleName));
Q_ASSERT(!candidate.isNull());
if (candidate->metaObject()->className()
== QApplication::style()->metaObject()->className()) {
action->trigger();
return;
}
delete candidate;
}
}
//! [31]

View File

@ -49,9 +49,10 @@
QT_BEGIN_NAMESPACE
class QAction;
class QActionGroup;
class QGroupBox;
class QLabel;
class QMenu;
class QRadioButton;
class QButtonGroup;
class QTableWidget;
QT_END_NAMESPACE
class IconPreviewArea;
@ -65,51 +66,47 @@ class MainWindow : public QMainWindow
public:
MainWindow();
void loadImages(const QStringList &fileNames);
void show();
private slots:
void about();
void changeStyle(bool checked);
void changeSize(bool checked = true);
void changeSize(int, bool);
void triggerChangeSize();
void changeIcon();
void addImages();
void addSampleImages();
void addOtherImages();
void removeAllImages();
void useHighDpiPixmapsChanged(int checkState);
void screenChanged();
private:
void createPreviewGroupBox();
void createImagesGroupBox();
void createIconSizeGroupBox();
QWidget *createImagesGroupBox();
QWidget *createIconSizeGroupBox();
QWidget *createHighDpiIconSizeGroupBox();
void createActions();
void createMenus();
void createContextMenu();
void checkCurrentStyle();
void addImages(const QString &directory);
QWidget *centralWidget;
QGroupBox *previewGroupBox;
IconPreviewArea *previewArea;
QGroupBox *imagesGroupBox;
QTableWidget *imagesTable;
QGroupBox *iconSizeGroupBox;
QRadioButton *smallRadioButton;
QRadioButton *largeRadioButton;
QRadioButton *toolBarRadioButton;
QRadioButton *listViewRadioButton;
QRadioButton *iconViewRadioButton;
QRadioButton *tabBarRadioButton;
QRadioButton *otherRadioButton;
QButtonGroup *sizeButtonGroup;
IconSizeSpinBox *otherSpinBox;
QMenu *fileMenu;
QMenu *viewMenu;
QMenu *helpMenu;
QAction *addImagesAct;
QLabel *devicePixelRatioLabel;
QLabel *screenNameLabel;
QAction *addOtherImagesAct;
QAction *addSampleImagesAct;
QAction *removeAllImagesAct;
QAction *exitAct;
QAction *guessModeStateAct;
QAction *nativeFileDialogAct;
QActionGroup *styleActionGroup;
QAction *aboutAct;
QAction *aboutQtAct;
};
//! [0]

View File

@ -47,19 +47,20 @@
//! [0]
ImageViewer::ImageViewer()
: imageLabel(new QLabel)
, scrollArea(new QScrollArea)
, scaleFactor(1)
{
imageLabel = new QLabel;
imageLabel->setBackgroundRole(QPalette::Base);
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
imageLabel->setScaledContents(true);
scrollArea = new QScrollArea;
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageLabel);
scrollArea->setVisible(false);
setCentralWidget(scrollArea);
createActions();
createMenus();
resize(QGuiApplication::primaryScreen()->availableSize() * 3 / 5);
}
@ -71,53 +72,99 @@ bool ImageViewer::loadFile(const QString &fileName)
{
QImageReader reader(fileName);
reader.setAutoTransform(true);
const QImage image = reader.read();
if (image.isNull()) {
const QImage newImage = reader.read();
if (newImage.isNull()) {
QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName)));
setWindowFilePath(QString());
imageLabel->setPixmap(QPixmap());
imageLabel->adjustSize();
tr("Cannot load %1: %2")
.arg(QDir::toNativeSeparators(fileName)), reader.errorString());
return false;
}
//! [2] //! [3]
//! [2]
setImage(newImage);
setWindowFilePath(fileName);
const QString message = tr("Opened \"%1\", %2x%3, Depth: %4")
.arg(QDir::toNativeSeparators(fileName)).arg(image.width()).arg(image.height()).arg(image.depth());
statusBar()->showMessage(message);
return true;
}
void ImageViewer::setImage(const QImage &newImage)
{
image = newImage;
imageLabel->setPixmap(QPixmap::fromImage(image));
//! [3] //! [4]
//! [4]
scaleFactor = 1.0;
scrollArea->setVisible(true);
printAct->setEnabled(true);
fitToWindowAct->setEnabled(true);
updateActions();
if (!fitToWindowAct->isChecked())
imageLabel->adjustSize();
setWindowFilePath(fileName);
return true;
}
//! [4]
//! [2]
bool ImageViewer::saveFile(const QString &fileName)
{
QImageWriter writer(fileName);
if (!writer.write(image)) {
QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
tr("Cannot write %1: %2")
.arg(QDir::toNativeSeparators(fileName)), writer.errorString());
return false;
}
const QString message = tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(fileName));
statusBar()->showMessage(message);
return true;
}
//! [1]
void ImageViewer::open()
static void initializeImageFileDialog(QFileDialog &dialog, QFileDialog::AcceptMode acceptMode)
{
static bool firstDialog = true;
if (firstDialog) {
firstDialog = false;
const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
dialog.setDirectory(picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last());
}
QStringList mimeTypeFilters;
foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes())
const QByteArrayList supportedMimeTypes = acceptMode == QFileDialog::AcceptOpen
? QImageReader::supportedMimeTypes() : QImageWriter::supportedMimeTypes();
foreach (const QByteArray &mimeTypeName, supportedMimeTypes)
mimeTypeFilters.append(mimeTypeName);
mimeTypeFilters.sort();
const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
QFileDialog dialog(this, tr("Open File"),
picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last());
dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setMimeTypeFilters(mimeTypeFilters);
dialog.selectMimeTypeFilter("image/jpeg");
if (acceptMode == QFileDialog::AcceptSave)
dialog.setDefaultSuffix("jpg");
}
void ImageViewer::open()
{
QFileDialog dialog(this, tr("Open File"));
initializeImageFileDialog(dialog, QFileDialog::AcceptOpen);
while (dialog.exec() == QDialog::Accepted && !loadFile(dialog.selectedFiles().first())) {}
}
//! [1]
void ImageViewer::saveAs()
{
QFileDialog dialog(this, tr("Save File As"));
initializeImageFileDialog(dialog, QFileDialog::AcceptSave);
while (dialog.exec() == QDialog::Accepted && !saveFile(dialog.selectedFiles().first())) {}
}
//! [5]
void ImageViewer::print()
//! [5] //! [6]
@ -140,6 +187,43 @@ void ImageViewer::print()
}
//! [8]
void ImageViewer::copy()
{
#ifndef QT_NO_CLIPBOARD
QGuiApplication::clipboard()->setImage(image);
#endif // !QT_NO_CLIPBOARD
}
#ifndef QT_NO_CLIPBOARD
static QImage clipboardImage()
{
if (const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData()) {
if (mimeData->hasImage()) {
const QImage image = qvariant_cast<QImage>(mimeData->imageData());
if (!image.isNull())
return image;
}
}
return QImage();
}
#endif // !QT_NO_CLIPBOARD
void ImageViewer::paste()
{
#ifndef QT_NO_CLIPBOARD
const QImage newImage = clipboardImage();
if (newImage.isNull()) {
statusBar()->showMessage(tr("No image in clipboard"));
} else {
setImage(newImage);
setWindowFilePath(QString());
const QString message = tr("Obtained image from clipboard, %1x%2, Depth: %3")
.arg(newImage.width()).arg(newImage.height()).arg(newImage.depth());
statusBar()->showMessage(message);
}
#endif // !QT_NO_CLIPBOARD
}
//! [9]
void ImageViewer::zoomIn()
//! [9] //! [10]
@ -167,9 +251,8 @@ void ImageViewer::fitToWindow()
{
bool fitToWindow = fitToWindowAct->isChecked();
scrollArea->setWidgetResizable(fitToWindow);
if (!fitToWindow) {
if (!fitToWindow)
normalSize();
}
updateActions();
}
//! [14]
@ -199,79 +282,66 @@ void ImageViewer::about()
void ImageViewer::createActions()
//! [17] //! [18]
{
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcut(tr("Ctrl+O"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
printAct = new QAction(tr("&Print..."), this);
printAct->setShortcut(tr("Ctrl+P"));
QAction *openAct = fileMenu->addAction(tr("&Open..."), this, &ImageViewer::open);
openAct->setShortcut(QKeySequence::Open);
saveAsAct = fileMenu->addAction(tr("&Save As..."), this, &ImageViewer::saveAs);
saveAsAct->setEnabled(false);
printAct = fileMenu->addAction(tr("&Print..."), this, &ImageViewer::print);
printAct->setShortcut(QKeySequence::Print);
printAct->setEnabled(false);
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
fileMenu->addSeparator();
QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
zoomInAct = new QAction(tr("Zoom &In (25%)"), this);
zoomInAct->setShortcut(tr("Ctrl++"));
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
copyAct = editMenu->addAction(tr("&Copy"), this, &ImageViewer::copy);
copyAct->setShortcut(QKeySequence::Copy);
copyAct->setEnabled(false);
QAction *pasteAct = editMenu->addAction(tr("&Paste"), this, &ImageViewer::paste);
pasteAct->setShortcut(QKeySequence::Paste);
QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
zoomInAct = viewMenu->addAction(tr("Zoom &In (25%)"), this, &ImageViewer::zoomIn);
zoomInAct->setShortcut(QKeySequence::ZoomIn);
zoomInAct->setEnabled(false);
connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));
zoomOutAct = new QAction(tr("Zoom &Out (25%)"), this);
zoomOutAct->setShortcut(tr("Ctrl+-"));
zoomOutAct = viewMenu->addAction(tr("Zoom &Out (25%)"), this, &ImageViewer::zoomOut);
zoomOutAct->setShortcut(QKeySequence::ZoomOut);
zoomOutAct->setEnabled(false);
connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));
normalSizeAct = new QAction(tr("&Normal Size"), this);
normalSizeAct = viewMenu->addAction(tr("&Normal Size"), this, &ImageViewer::normalSize);
normalSizeAct->setShortcut(tr("Ctrl+S"));
normalSizeAct->setEnabled(false);
connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));
fitToWindowAct = new QAction(tr("&Fit to Window"), this);
viewMenu->addSeparator();
fitToWindowAct = viewMenu->addAction(tr("&Fit to Window"), this, &ImageViewer::fitToWindow);
fitToWindowAct->setEnabled(false);
fitToWindowAct->setCheckable(true);
fitToWindowAct->setShortcut(tr("Ctrl+F"));
connect(fitToWindowAct, SIGNAL(triggered()), this, SLOT(fitToWindow()));
aboutAct = new QAction(tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
aboutQtAct = new QAction(tr("About &Qt"), this);
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
helpMenu->addAction(tr("&About"), this, &ImageViewer::about);
helpMenu->addAction(tr("About &Qt"), &QApplication::aboutQt);
}
//! [18]
//! [19]
void ImageViewer::createMenus()
//! [19] //! [20]
{
fileMenu = new QMenu(tr("&File"), this);
fileMenu->addAction(openAct);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
viewMenu = new QMenu(tr("&View"), this);
viewMenu->addAction(zoomInAct);
viewMenu->addAction(zoomOutAct);
viewMenu->addAction(normalSizeAct);
viewMenu->addSeparator();
viewMenu->addAction(fitToWindowAct);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(viewMenu);
menuBar()->addMenu(helpMenu);
}
//! [20]
//! [21]
void ImageViewer::updateActions()
//! [21] //! [22]
{
saveAsAct->setEnabled(!image.isNull());
copyAct->setEnabled(!image.isNull());
zoomInAct->setEnabled(!fitToWindowAct->isChecked());
zoomOutAct->setEnabled(!fitToWindowAct->isChecked());
normalSizeAct->setEnabled(!fitToWindowAct->isChecked());

View File

@ -42,6 +42,7 @@
#define IMAGEVIEWER_H
#include <QMainWindow>
#include <QImage>
#ifndef QT_NO_PRINTER
#include <QPrinter>
#endif
@ -65,7 +66,10 @@ public:
private slots:
void open();
void saveAs();
void print();
void copy();
void paste();
void zoomIn();
void zoomOut();
void normalSize();
@ -76,9 +80,12 @@ private:
void createActions();
void createMenus();
void updateActions();
bool saveFile(const QString &fileName);
void setImage(const QImage &newImage);
void scaleImage(double factor);
void adjustScrollBar(QScrollBar *scrollBar, double factor);
QImage image;
QLabel *imageLabel;
QScrollArea *scrollArea;
double scaleFactor;
@ -87,19 +94,13 @@ private:
QPrinter printer;
#endif
QAction *openAct;
QAction *saveAsAct;
QAction *printAct;
QAction *exitAct;
QAction *copyAct;
QAction *zoomInAct;
QAction *zoomOutAct;
QAction *normalSizeAct;
QAction *fitToWindowAct;
QAction *aboutAct;
QAction *aboutQtAct;
QMenu *fileMenu;
QMenu *viewMenu;
QMenu *helpMenu;
};
//! [0]

View File

@ -27,9 +27,15 @@ QMAKE_CXXFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
QMAKE_CXXFLAGS_DISABLE_LTCG = $$QMAKE_CFLAGS_DISABLE_LTCG
QMAKE_CXXFLAGS_CXX11 = -std=c++11
QMAKE_CXXFLAGS_CXX14 = -std=c++1y
QMAKE_CXXFLAGS_CXX1Z = -std=c++1z
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++11
QMAKE_CXXFLAGS_GNUCXX14 = -std=gnu++1y
QMAKE_CXXFLAGS_GNUCXX1Z = -std=gnu++1z
QMAKE_LFLAGS_CXX11 =
QMAKE_LFLAGS_CXX14 =
QMAKE_LFLAGS_CXX1Z =
QMAKE_LFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
# Wrapper tools that understand .o/.a files with LLVM bytecode instead of machine code

View File

@ -28,5 +28,11 @@ QMAKE_CXXFLAGS_PRECOMPILE = -x c++-header -c ${QMAKE_PCH_INPUT} -o ${QMAKE_P
QMAKE_CXXFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
QMAKE_CXXFLAGS_CXX11 = -std=c++0x
QMAKE_CXXFLAGS_CXX14 = -std=c++1y
QMAKE_CXXFLAGS_CXX1Z = -std=c++1z
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++0x
QMAKE_CXXFLAGS_GNUCXX14 = -std=gnu++1y
QMAKE_CXXFLAGS_GNUCXX1Z = -std=gnu++1z
QMAKE_LFLAGS_CXX11 =
QMAKE_LFLAGS_CXX14 =
QMAKE_LFLAGS_CXX1Z =

View File

@ -22,3 +22,4 @@ QMAKE_LFLAGS_USE_GOLD = -fuse-ld=gold
# -Bsymbolic-functions (ld) support
QMAKE_LFLAGS_BSYMBOLIC_FUNC = -Wl,-Bsymbolic-functions
QMAKE_LFLAGS_DYNAMIC_LIST = -Wl,--dynamic-list,
QMAKE_LFLAGS_VERSION_SCRIPT = -Wl,--version-script,

View File

@ -62,6 +62,7 @@
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#define __APPLE_USE_RFC_3542
#include <netinet/in.h>
#ifndef QT_NO_IPV6IFNAME
#include <net/if.h>

View File

@ -140,7 +140,7 @@ greaterThan(MSC_VER, 1899) {
QMAKE_CFLAGS += -Zc:strictStrings
QMAKE_CFLAGS_WARN_ON += -w44456 -w44457 -w44458
QMAKE_CFLAGS_AVX2 = -arch:AVX2
QMAKE_CXXFLAGS += -Zc:strictStrings
QMAKE_CXXFLAGS += -Zc:strictStrings -Zc:throwingNew
QMAKE_CXXFLAGS_WARN_ON += -w44456 -w44457 -w44458 -wd4577
}

View File

@ -19,6 +19,7 @@ QMAKE_LFLAGS_RPATHLINK = -Wl,-rpath-link,
# -Bsymbolic-functions (ld) support
QMAKE_LFLAGS_BSYMBOLIC_FUNC = -Wl,-Bsymbolic-functions
QMAKE_LFLAGS_DYNAMIC_LIST = -Wl,--dynamic-list,
QMAKE_LFLAGS_VERSION_SCRIPT = -Wl,--version-script,
# Generic options for all BlackBerry/QNX qcc mkspecs
QMAKE_CFLAGS_THREAD = -D_REENTRANT
@ -45,6 +46,8 @@ QMAKE_LIBDIR = $${QNX_DIR}/$${QNX_CPUDIR}/lib $${QNX_DIR}/$${QNX_CPUD
QMAKE_LFLAGS += -Wl,-rpath-link,$${QNX_DIR}/$${QNX_CPUDIR}/lib -Wl,-rpath-link,$${QNX_DIR}/$${QNX_CPUDIR}/usr/lib
QMAKE_CXXFLAGS_CXX11 = -Wc,-std=gnu++0x
QMAKE_CXXFLAGS_CXX14 = -Wc,-std=gnu++1y
QMAKE_CXXFLAGS_CXX1Z = -Wc,-std=gnu++1z
QMAKE_LINK_C = $$QMAKE_CC
QMAKE_LINK_C_SHLIB = $$QMAKE_CC

View File

@ -9,7 +9,8 @@
<Identity
Name=\"$${WINRT_MANIFEST.identity}\"
Publisher=\"$${WINRT_MANIFEST.publisherid}\"
Version=\"$${WINRT_MANIFEST.version}\" />
Version=\"$${WINRT_MANIFEST.version}\"
ProcessorArchitecture=\"$${WINRT_MANIFEST.architecture}\" />
<mp:PhoneIdentity PhoneProductId=\"$${WINRT_MANIFEST.identity}\" PhonePublisherId=\"$${WINRT_MANIFEST.phone_publisher_id}\"/>
@ -20,7 +21,7 @@
</Properties>
<Dependencies>
<TargetDeviceFamily Name=\"Windows.Universal\" MinVersion=\"10.0.10069.0\" MaxVersionTested=\"10.0.10069.0\" />
<TargetDeviceFamily Name=\"Windows.Universal\" MinVersion=\"10.0.10069.0\" MaxVersionTested=\"10.0.10069.0\" />$${WINRT_MANIFEST.dependencies}
</Dependencies>
<Resources>

View File

@ -41,6 +41,8 @@
<m2:SplashScreen Image=\"$${WINRT_MANIFEST.logo_620x300}\" />$${WINRT_MANIFEST.rotation_preference}
</m2:VisualElements>
</Application>
</Applications>$${WINRT_MANIFEST.capabilities}$${WINRT_MANIFEST.dependencies}
</Applications>$${WINRT_MANIFEST.capabilities}
<Dependencies>$${WINRT_MANIFEST.dependencies}
</Dependencies>
</Package>
<!-- Generated by qmake using the $$[QMAKE_XSPEC] mkspec. -->

View File

@ -42,6 +42,8 @@
<m3:SplashScreen Image=\"$${WINRT_MANIFEST.logo_480x800}\" />$${WINRT_MANIFEST.rotation_preference}
</m3:VisualElements>
</Application>
</Applications>$${WINRT_MANIFEST.capabilities}$${WINRT_MANIFEST.dependencies}
</Applications>$${WINRT_MANIFEST.capabilities}
<Dependencies>$${WINRT_MANIFEST.dependencies}
</Dependencies>
</Package>
<!-- Generated by qmake using the $$[QMAKE_XSPEC] mkspec. -->

View File

@ -7,7 +7,7 @@
MAKEFILE_GENERATOR = MSBUILD
QMAKE_COMPILER = msvc
QMAKE_PLATFORM = winrt win32
CONFIG += incremental flat precompile_header autogen_precompile_source debug_and_release debug_and_release_target no_generated_target_info package_manifest rtti
CONFIG += incremental flat precompile_header autogen_precompile_source debug_and_release debug_and_release_target package_manifest rtti
DEFINES += UNICODE WIN32 QT_LARGEFILE_SUPPORT Q_BYTE_ORDER=Q_LITTLE_ENDIAN \
QT_NO_PRINTER QT_NO_PRINTDIALOG # TODO: Remove when printing is re-enabled

View File

@ -3,6 +3,10 @@ contains(DISTRO_OPTS, deb-multi-arch) {
-Wl,-rpath-link,$$[QT_SYSROOT]/lib/$${GCC_MACHINE_DUMP}
}
contains(DISTRO_OPTS, boot2qt) {
QMAKE_PLATFORM += boot2qt
}
QMAKE_CFLAGS += $$COMPILER_FLAGS
QMAKE_CXXFLAGS += $$COMPILER_FLAGS
QMAKE_LFLAGS += $$LINKER_FLAGS

View File

@ -0,0 +1,20 @@
#
# qmake configuration for the Intel NUC DE3815TYKE targeting EGL/GLES either via KMS (eglfs) or Wayland
#
# Verified with a core-image-weston image produced by Yocto.
include(../common/linux_device_pre.conf)
QMAKE_LIBS_EGL += -lEGL
QMAKE_LIBS_OPENGL_ES2 += -lGLESv2 -lEGL
NUC_CFLAGS = -m64
QMAKE_CFLAGS += $$NUC_CFLAGS
QMAKE_CXXFLAGS += $$NUC_CFLAGS
# Preferred eglfs backend
EGLFS_DEVICE_INTEGRATION = eglfs_kms
include(../common/linux_device_post.conf)
load(qt_config)

View File

@ -3,7 +3,7 @@
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
** This file is part of the qmake spec of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
@ -31,27 +31,4 @@
**
****************************************************************************/
#ifndef QKMSWINDOW_H
#define QKMSWINDOW_H
#include <qpa/qplatformwindow.h>
QT_BEGIN_NAMESPACE
class QKmsWindow : public QPlatformWindow
{
Q_DECLARE_PRIVATE(QPlatformWindow)
public:
QKmsWindow(QWindow *window);
void setGeometry(const QRect &rect) Q_DECL_OVERRIDE;
QSurfaceFormat format() const Q_DECL_OVERRIDE;
private:
QPlatformScreen *m_screen;
};
QT_END_NAMESPACE
#endif // QKMSWINDOW_H
#include "../../linux-g++/qplatformdefs.h"

View File

@ -1,9 +0,0 @@
strict_c++|isEmpty(QMAKE_CXXFLAGS_GNUCXX11) {
QMAKE_CXXFLAGS += $$QMAKE_CXXFLAGS_CXX11
QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_CXXFLAGS_CXX11
QMAKE_LFLAGS += $$QMAKE_LFLAGS_CXX11
} else {
QMAKE_CXXFLAGS += $$QMAKE_CXXFLAGS_GNUCXX11
QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_CXXFLAGS_GNUCXX11
QMAKE_LFLAGS += $$QMAKE_LFLAGS_GNUCXX11
}

View File

@ -1,23 +0,0 @@
intel_icc {
# ICC does not support C++14 yet
} else: clang {
# Clang has supported -std=c++1y since version 3.2
greaterThan(QT_CLANG_MAJOR_VERSION, 3)|greaterThan(QT_CLANG_MINOR_VERSION, 1) {
QMAKE_CXXFLAGS_CXX11 = -std=c++1y
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++1y
}
# Unknown how long Apple Clang has supported -std=c++1y, but at least since XCode 5.0
greaterThan(QT_APPLE_CLANG_MAJOR_VERSION, 4) {
QMAKE_CXXFLAGS_CXX11 = -std=c++1y
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++1y
}
} else: gcc {
# GCC has supported -std=c++1y since 4.8
greaterThan(QT_GCC_MAJOR_VERSION, 4)|greaterThan(QT_GCC_MINOR_VERSION, 7) {
QMAKE_CXXFLAGS_CXX11 = -std=c++1y
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++1y
}
}
# Delegate to c++11.prf
include(c++11.prf)

View File

@ -98,6 +98,21 @@ breakpad {
!isEmpty(QMAKE_STRIP):QMAKE_POST_LINK = $$QMAKE_POST_LINK$$escape_expand(\\n\\t)$$quote($$QMAKE_STRIP $$DEBUGFILENAME)
}
c++11|c++14|c++1z {
c++1z: cxxstd = CXX1Z
else: c++14: cxxstd = CXX14
else: cxxstd = CXX11
# Check if we should disable the GNU extensions or not
!strict_c++:!isEmpty(QMAKE_CXXFLAGS_GNU$$cxxstd): cxxstd = GNU$$cxxstd
QMAKE_CXXFLAGS += $$eval(QMAKE_CXXFLAGS_$$cxxstd)
QMAKE_OBJECTIVE_CFLAGS += $$eval(QMAKE_CXXFLAGS_$$cxxstd)
QMAKE_LFLAGS += $$eval(QMAKE_LFLAGS_$$cxxstd)
unset(cxxstd)
}
!precompile_header: SOURCES += $$NO_PCH_SOURCES
QMAKE_INCDIR += $$QMAKE_INCDIR_POST

View File

@ -19,10 +19,15 @@ defineTest(deviceSanityCheckCompiler) {
else: \
sfx =
# Build the compiler filename using the first value in QMAKE_CXX in order to
# support tools like ccache, which give QMAKE_CXX values of the form:
# ccache <path_to_compiler>
compiler = $$first(QMAKE_CXX)$$sfx
# Check if the binary exists with an absolute path. Do this check
# before the CROSS_COMPILE empty check below to allow the mkspec
# to derive the compiler path from other device options.
exists($$QMAKE_CXX$$sfx):return()
exists($$compiler):return()
# Check for possible reasons of failure
# check if CROSS_COMPILE device-option is set
@ -31,7 +36,7 @@ defineTest(deviceSanityCheckCompiler) {
# Check if QMAKE_CXX points to an executable.
ensurePathEnv()
for (dir, QMAKE_PATH_ENV) {
exists($$dir/$${QMAKE_CXX}$$sfx): \
exists($$dir/$${compiler}): \
return()
}

View File

@ -26,7 +26,7 @@
$(MOVE) $$intermediate_file ${QMAKE_FILE_OUT} $$escape_expand(\\n\\t)
unset(intermediate_file)
}
lex.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_lex$${first(QMAKE_EXT_CPP)}
lex.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_LEX}$${first(QMAKE_EXT_CPP)}
silent:lex.commands = @echo Lex ${QMAKE_FILE_IN} && $$lex.commands
QMAKE_EXTRA_COMPILERS += lex

View File

@ -1,20 +1,7 @@
load(default_post)
!no_objective_c:CONFIG += objective_c
qt:!isEmpty(QT_CONFIG) {
# Pick a suitable default architecture for qmake-based applications.
# If the Qt package contains one of x86 and x86_64, pick that one. If it
# contains both then use the compiler default. Make a similar decision for
# PowerPC-based systems. Note that this logic assumes that Qt has been
# configured with an architecture that is usable on the system.
contains(QMAKE_HOST.arch, ppc)|contains(QMAKE_HOST.arch, "Power Macintosh") {
!contains(QT_CONFIG, ppc64):contains(QT_CONFIG, ppc):CONFIG += ppc
contains(QT_CONFIG, ppc64):!contains(QT_CONFIG, ppc):CONFIG += ppc64
} else {
!contains(QT_CONFIG, x86_64):contains(QT_CONFIG, x86):CONFIG += x86
contains(QT_CONFIG, x86_64):!contains(QT_CONFIG, x86):CONFIG += x86_64
}
qt {
contains(QT_CONFIG, static) {
# C++11 support means using libc++ instead of libstd++. As the
# two libraries are incompatible we need to ensure the end user
@ -35,31 +22,6 @@ qt:!isEmpty(QT_CONFIG) {
QMAKE_LFLAGS += -stdlib=libstdc++
}
}
# If Qt was built with shared libraries with rpath support and project does
# not specify own rpaths (including empty list) add one pointing to Qt
# libraries. This applies only to apps, since all loaded libraries inherit
# rpaths from current process executable.
else:!if(host_build:force_bootstrap):equals(TEMPLATE, app):!defined(QMAKE_RPATHDIR, var):contains(QT_CONFIG, rpath) {
# If app is expected to be installed into the Qt prefix build, use
# relative path, so all SDK tools and examples work when relocated.
prefix_build:defined(target.path, var):\
contains(target.path, "$$re_escape($$[QT_INSTALL_PREFIX])/.*"):\
# Tests are an exception, since they are launched in their build not
# install location by CI, so we cannot use relative rpaths there.
!contains(target.path, "$$re_escape($$[QT_INSTALL_TESTS])/.*") {
app_bundle {
ios: binpath = $$target.path/$${TARGET}.app
else: binpath = $$target.path/$${TARGET}.app/Contents/MacOS
} else {
binpath = $$target.path
}
QMAKE_RPATHDIR = @loader_path/$$relative_path($$[QT_INSTALL_LIBS], $$binpath)
unset(binpath)
} else {
# Otherwise, use absolute path to Qt libraries
QMAKE_RPATHDIR = $$[QT_INSTALL_LIBS]
}
}
}
macx-xcode:!isEmpty(QMAKE_XCODE_DEBUG_INFORMATION_FORMAT) {

View File

@ -72,9 +72,6 @@ isEmpty(QMAKE_MAC_SDK.$${QMAKE_MAC_SDK}.platform_name) {
# FIXME: Get the version_min_flag out of the platform's 'Native Build System.xcspec'
version_identifier = $$replace(QMAKE_MAC_PLATFORM_NAME, iphonesimulator, ios-simulator)
# C++11 support may affect the deployment target
c++11: load(c++11)
ios:!host_build: \
deployment_target = $$QMAKE_IOS_DEPLOYMENT_TARGET
else: \

View File

@ -14,18 +14,6 @@ no_keywords:DEFINES += QT_NO_KEYWORDS
plugin { #Qt plugins
static:DEFINES += QT_STATICPLUGIN
DEFINES += QT_PLUGIN
# Triggers both on Qt being configured with -arch boundschecker,
# and if you qmake CONFIG+=boundchecker on your plugin project
boundschecker|contains(QT_CONFIG,boundschecker) {
# This option is added for plugins when Qt is configured for Boundschecker,
# since we want Boundschecker to not instrument the qt_plugin_query_verification_data
# function, as we call that function without the plugin's dependent DLLs, thus
# Boundscheckers instrumentation will fail. The function only returns a const char *,
# so no instrumentation is really needed on that function anyways.
QMAKE_CFLAGS += /nmignore:*:qt_plugin_query_verification_data
QMAKE_CXXFLAGS += /nmignore:*:qt_plugin_query_verification_data
}
}
qtestlib {
@ -57,23 +45,155 @@ qaxserver {
QT += axserver
}
# target variable, flag source variable
defineTest(qtProcessModuleFlags) {
for(flag, $$2) {
contains(flag, ^-.*): \
$$1 -= $$replace(flag, ^-, )
else: \
$$1 += $$flag
}
export($$1)
}
unset(using_privates)
qtAddModules(QT, LIBS)
qtAddModules(QT_PRIVATE, LIBS_PRIVATE)
var_sfx =
for(ever) {
# qmake variables cannot contain dashes, so normalize the names first
CLEAN_QT$$var_sfx = $$replace(QT$$var_sfx, -private$, _private)
# Topological resolution of modules based on their QT.<module>.depends variable
FULL_QT$$var_sfx = $$resolve_depends(CLEAN_QT$$var_sfx, "QT.")
# Finally actually add the modules
unset(BAD_QT)
for(QTLIB, FULL_QT$$var_sfx) {
MODULE_NAME = $$eval(QT.$${QTLIB}.name)
MODULE_INCLUDES = $$eval(QT.$${QTLIB}.includes)
MODULE_LIBS = $$eval(QT.$${QTLIB}.libs)
MODULE_CONFIG = $$eval(QT.$${QTLIB}.module_config)
isEmpty(MODULE_NAME) {
BAD_QT += $$QTLIB
next()
}
target_qt:isEqual(TARGET, $$MODULE_NAME) {
warning("$$TARGET cannot have a QT$$var_sfx of $$QTLIB")
next()
}
contains(MODULE_CONFIG, internal_module): \
using_privates = true
contains(MODULE_CONFIG, ltcg): \
CONFIG += link_ltcg
qtProcessModuleFlags(CONFIG, QT.$${QTLIB}.CONFIG)
qtProcessModuleFlags(DEFINES, QT.$${QTLIB}.DEFINES)
MODULE_INCLUDES -= $$QMAKE_DEFAULT_INCDIRS
MODULE_LIBS_ADD = $$MODULE_LIBS
MODULE_LIBS_ADD -= $$QMAKE_DEFAULT_LIBDIRS
LINKAGE =
mac:contains(MODULE_CONFIG, lib_bundle) {
FRAMEWORK_INCLUDE = $${MODULE_LIBS}/$${MODULE_NAME}.framework/Headers
!qt_no_framework_direct_includes {
INCLUDEPATH *= $$FRAMEWORK_INCLUDE
}
contains(MODULE_CONFIG, internal_module): \
INCLUDEPATH += \
$$FRAMEWORK_INCLUDE/$$eval(QT.$${QTLIB}.VERSION) \
$$FRAMEWORK_INCLUDE/$$eval(QT.$${QTLIB}.VERSION)/$$MODULE_NAME
QMAKE_FRAMEWORKPATH *= $${MODULE_LIBS}
!contains(MODULE_CONFIG, no_link): \
LINKAGE += -framework $${MODULE_NAME}$${QT_LIBINFIX}
} else {
INCLUDEPATH *= $$MODULE_INCLUDES
}
# Only link to this module if a libs directory is set, else this is just a module
# to give access to sources or include files, and not for linking.
!isEmpty(MODULE_LIBS):!contains(MODULE_CONFIG, no_link) {
# Re-insert the major version in the library name (cf qt5LibraryTarget above)
# unless it's a framework build
!mac|!contains(MODULE_CONFIG, lib_bundle): \
MODULE_NAME ~= s,^Qt,Qt$$QT_MAJOR_VERSION,
win32 {
# Make sure the version number isn't appended again to the lib name
QMAKE_$${upper($$MODULE_NAME$$QT_LIBINFIX)}_VERSION_OVERRIDE = 0
QMAKE_$${upper($$MODULE_NAME$$QT_LIBINFIX)}D_VERSION_OVERRIDE = 0
}
isEmpty(LINKAGE) {
!isEmpty(MODULE_LIBS_ADD): \
LINKAGE = -L$$MODULE_LIBS_ADD
lib = $${MODULE_NAME}$${QT_LIBINFIX}$$qtPlatformTargetSuffix()
LINKAGE += -l$$lib
contains(MODULE_CONFIG, staticlib): \
PRE_TARGETDEPS *= $$MODULE_LIBS/$${QMAKE_PREFIX_STATICLIB}$${lib}.$${QMAKE_EXTENSION_STATICLIB}
}
LIBS$$var_sfx += $$LINKAGE
!isEmpty(QMAKE_LSB) {
!isEmpty(MODULE_LIBS_ADD): \
QMAKE_LFLAGS *= --lsb-libpath=$$MODULE_LIBS_ADD
QMAKE_LFLAGS *= --lsb-shared-libs=$${MODULE_NAME}$${QT_LIBINFIX}
QMAKE_LIBDIR *= /opt/lsb/lib
}
}
}
!isEmpty(BAD_QT):error("Unknown module(s) in QT$$var_sfx: $$replace(BAD_QT, _private$, -private)")
!isEmpty(var_sfx): break()
var_sfx = _PRIVATE
}
!isEmpty(using_privates):!no_private_qt_headers_warning:if(!debug_and_release|!build_pass) {
message("This project is using private headers and will therefore be tied to this specific Qt module build version.")
message("Running this project against other versions of the Qt modules may crash at any arbitrary point.")
message("This is not a bug, but a result of using Qt internals. You have been warned!")
}
qtAddRpathLink($$QT $$QT_PRIVATE)
wince:static:gui {
QTLIB += qmenu_wce.res
qt_module_deps = $$CLEAN_QT $$CLEAN_QT_PRIVATE
qt_module_deps = $$resolve_depends(qt_module_deps, "QT.")
!no_qt_rpath:!static:contains(QT_CONFIG, rpath):!contains(QT_CONFIG, static):\
contains(qt_module_deps, core) {
relative_qt_rpath:defined(target.path, var) {
mac {
if(equals(TEMPLATE, app):app_bundle)|\
if(equals(TEMPLATE, lib):plugin:plugin_bundle) {
ios: binpath = $$target.path/$${TARGET}.app
else: binpath = $$target.path/$${TARGET}.app/Contents/MacOS
} else: equals(TEMPLATE, lib):!plugin:lib_bundle {
binpath = $$target.path/$${TARGET}.framework/Versions/Current
} else {
binpath = $$target.path
}
QMAKE_RPATHDIR += @loader_path/$$relative_path($$[QT_INSTALL_LIBS], $$binpath)
} else {
QMAKE_LFLAGS += -Wl,-z,origin
QMAKE_RPATHDIR += $ORIGIN/$$relative_path($$[QT_INSTALL_LIBS], $$target.path)
}
} else {
QMAKE_RPATHDIR += $$[QT_INSTALL_LIBS/dev]
}
}
qt_module_deps = $$QT $$QT_PRIVATE
qt_module_deps = $$replace(qt_module_deps, -private$, _private)
qt_module_deps = $$resolve_depends(qt_module_deps, "QT.")
!isEmpty(QMAKE_LFLAGS_RPATHLINK):!contains(QT_CONFIG, static) {
# -rpath-link is used by the linker to find dependencies of dynamic
# libraries which were NOT specified on the command line.
# This means that paths of direct dependencies (QT & QT_PRIVATE)
# don't need to be listed, unlike their private dependencies' paths.
privdep = $$resolve_depends(qt_module_deps, "QT.", ".depends" ".run_depends")
privdep -= $$qt_module_deps
rpaths =
for(dep, privdep): \
rpaths += $$eval(QT.$${dep}.libs)
QMAKE_RPATHLINKDIR *= $$unique(rpaths)
}
# static builds: link qml import plugins into the app.
contains(qt_module_deps, qml): \

View File

@ -30,6 +30,7 @@ host_build:force_bootstrap {
} else {
!build_pass:contains(QT_CONFIG, debug_and_release):contains(QT_CONFIG, build_all): CONFIG += release
target.path = $$[QT_INSTALL_BINS]
CONFIG += relative_qt_rpath # Qt's tools and apps should be relocatable
}
INSTALLS += target

View File

@ -13,6 +13,8 @@ QMAKE_DIR_REPLACE_SANE += DESTDIR
CONFIG -= debug_and_release_target
contains(QT_CONFIG, c++11): CONFIG += c++11 strict_c++
contains(QT_CONFIG, c++14): CONFIG += c++14
contains(QT_CONFIG, c++1z): CONFIG += c++1z
contains(TEMPLATE, .*lib) {
# module and plugins
!host_build:contains(QT_CONFIG, reduce_exports): CONFIG += hide_symbols
@ -46,18 +48,18 @@ warnings_are_errors:warning_clean {
# If the module declares that it has does its clean-up of warnings, enable -Werror.
# This setting is compiler-dependent anyway because it depends on the version of the
# compiler.
clang {
# Apple clang 4.0-4.2,5.0-5.1
# Regular clang 3.3-3.6
clang:!ios {
# Apple clang 4.0-4.2,5.0-5.1,6.0-6.4
# Regular clang 3.3-3.7
apple_ver = $${QT_APPLE_CLANG_MAJOR_VERSION}.$${QT_APPLE_CLANG_MINOR_VERSION}
reg_ver = $${QT_CLANG_MAJOR_VERSION}.$${QT_CLANG_MINOR_VERSION}
contains(apple_ver, "4\\.[012]|5\\.[01]")|contains(reg_ver, "3\\.[3-6]") {
contains(apple_ver, "4\\.[012]|5\\.[01]|6\\.[01234]")|contains(reg_ver, "3\\.[3-7]") {
QMAKE_CXXFLAGS_WARN_ON += -Werror -Wno-error=\\$${LITERAL_HASH}warnings -Wno-error=deprecated-declarations $$WERROR
}
} else:intel_icc:linux {
# Intel CC 13.0 - 15.0, on Linux only
# Intel CC 13.0 - 16.0, on Linux only
ver = $${QT_ICC_MAJOR_VERSION}.$${QT_ICC_MINOR_VERSION}
linux:contains(ver, "(1[34]\\.|15\\.0)") {
linux:contains(ver, "(1[345]\\.|16\\.0)") {
# 177: function "entity" was declared but never referenced
# (too aggressive; ICC reports even for functions created due to template instantiation)
# 1224: #warning directive

View File

@ -9,6 +9,8 @@
# We mean it.
#
contains(TEMPLATE, "vc.*"): return()
defineTest(addInstallFiles) {
for(sf, 2) {
sf = $$relative_path($$sf, $$_PRO_FILE_PWD_)
@ -99,5 +101,7 @@ probase = $$relative_path($$_PRO_FILE_PWD_, $$dirname(_QMAKE_CONF_)/examples)
SOURCES =
OBJECTIVE_SOURCES =
INSTALLS -= target
} else {
CONFIG += relative_qt_rpath # Examples built as part of Qt should be relocatable
}
}

View File

@ -38,24 +38,14 @@ defineTest(qtAddLibrary) {
# Reverse-engineer the module name from the library name.
for(var, QT_MODULES) {
isEqual(QT.$${var}.name, $$1) {
qtAddModule($$var, LIBS)
QT += $$var
export(QT)
return(true)
}
}
error("No module matching library '$$1' found.")
}
# target variable, flag source variable
defineTest(qtProcessModuleFlags) {
for(flag, $$2) {
contains(flag, ^-.*): \
$$1 -= $$replace(flag, ^-, )
else: \
$$1 += $$flag
}
export($$1)
}
# qt module
defineTest(qtHaveModule) {
!isEmpty(QT.$$replace(1, -, _).name): \
@ -63,137 +53,6 @@ defineTest(qtHaveModule) {
return(false)
}
# qt module, libs variable
defineTest(qtAddModule) {
MODULE_NAME = $$eval(QT.$${1}.name)
MODULE_INCLUDES = $$eval(QT.$${1}.includes)
MODULE_LIBS = $$eval(QT.$${1}.libs)
MODULE_CONFIG = $$eval(QT.$${1}.module_config)
contains(MODULE_CONFIG, internal_module) {
using_privates = true
export(using_privates)
}
contains(MODULE_CONFIG, ltcg): CONFIG += link_ltcg
qtProcessModuleFlags(CONFIG, QT.$${1}.CONFIG)
qtProcessModuleFlags(DEFINES, QT.$${1}.DEFINES)
MODULE_INCLUDES -= $$QMAKE_DEFAULT_INCDIRS
MODULE_LIBS_ADD = $$MODULE_LIBS
MODULE_LIBS_ADD -= $$QMAKE_DEFAULT_LIBDIRS
unset(LINKAGE)
mac:contains(MODULE_CONFIG, lib_bundle) {
FRAMEWORK_INCLUDE = $${MODULE_LIBS}/$${MODULE_NAME}.framework/Headers
!qt_no_framework_direct_includes {
INCLUDEPATH *= $$FRAMEWORK_INCLUDE
}
contains(MODULE_CONFIG, internal_module): \
INCLUDEPATH += \
$$FRAMEWORK_INCLUDE/$$eval(QT.$${1}.VERSION) \
$$FRAMEWORK_INCLUDE/$$eval(QT.$${1}.VERSION)/$$MODULE_NAME
QMAKE_FRAMEWORKPATH *= $${MODULE_LIBS}
export(QMAKE_FRAMEWORKPATH)
!contains(MODULE_CONFIG, no_link): \
LINKAGE += -framework $${MODULE_NAME}$${QT_LIBINFIX}
} else {
INCLUDEPATH *= $$MODULE_INCLUDES
}
export(INCLUDEPATH)
# Only link to this module if a libs directory is set, else this is just a module
# to give access to sources or include files, and not for linking.
!isEmpty(MODULE_LIBS):!contains(MODULE_CONFIG, no_link) {
# Re-insert the major version in the library name (cf qt5LibraryTarget above)
# unless it's a framework build
!mac|!contains(MODULE_CONFIG, lib_bundle): \
MODULE_NAME ~= s,^Qt,Qt$$QT_MAJOR_VERSION,
win32 {
# Make sure the version number isn't appended again to the lib name
ver_var = QMAKE_$${upper($$MODULE_NAME$$QT_LIBINFIX)}_VERSION_OVERRIDE
dver_var = QMAKE_$${upper($$MODULE_NAME$$QT_LIBINFIX)}D_VERSION_OVERRIDE
$$ver_var = 0
$$dver_var = 0
export($$ver_var)
export($$dver_var)
}
isEmpty(LINKAGE) {
!isEmpty(MODULE_LIBS_ADD): \
LINKAGE = -L$$MODULE_LIBS_ADD
lib = $${MODULE_NAME}$${QT_LIBINFIX}$$qtPlatformTargetSuffix()
LINKAGE += -l$$lib
contains(QT_CONFIG, rpath) {
QMAKE_RPATHDIR *= $$eval(QT.$${1}.rpath)
export(QMAKE_RPATHDIR)
}
contains(MODULE_CONFIG, staticlib) {
PRE_TARGETDEPS *= $$MODULE_LIBS/$${QMAKE_PREFIX_STATICLIB}$${lib}.$${QMAKE_EXTENSION_STATICLIB}
export(PRE_TARGETDEPS)
}
}
$$2 += $$LINKAGE
export($$2)
!isEmpty(QMAKE_LSB) {
!isEmpty(MODULE_LIBS_ADD): \
QMAKE_LFLAGS *= --lsb-libpath=$$MODULE_LIBS_ADD
QMAKE_LFLAGS *= --lsb-shared-libs=$${MODULE_NAME}$${QT_LIBINFIX}
QMAKE_LIBDIR *= /opt/lsb/lib
export(QMAKE_LFLAGS)
export(QMAKE_LIBDIR)
}
}
}
# qt variable, libs variable
defineTest(qtAddModules) {
# qmake variables cannot contain dashes, so normalize the names first
$$1 = $$replace($$1, -private$, _private)
# Topological resolution of modules based on their QT.<module>.depends variable
$$1 = $$resolve_depends($$1, "QT.")
# Finally actually add the modules
unset(BAD_QT)
for(QTLIB, $$1) {
QTLIBNAME = $$eval(QT.$${QTLIB}.name)
isEmpty(QTLIBNAME) {
BAD_QT += $$QTLIB
next()
}
target_qt:isEqual(TARGET, $$QTLIBNAME) {
warning("$$TARGET cannot have a $$1 of $$QTLIB")
next()
}
qtAddModule($$QTLIB, $$2)
}
!isEmpty(BAD_QT):error("Unknown module(s) in $$1: $$replace(BAD_QT, _private$, -private)")
}
defineTest(qtAddRpathLink) {
# -rpath-link is used by the linker to find dependencies of dynamic
# libraries which were NOT specified on the command line.
# This means that paths of direct dependencies (QT & QT_PRIVATE)
# don't need to appear here. However, their private dependencies'
# paths OTOH need to be put there.
pubqt = $$replace(1, -private$, _private)
pubdep = $$resolve_depends(pubqt, "QT.")
privdep = $$resolve_depends(pubqt, "QT.", ".depends" ".run_depends")
privdep -= $$pubdep
rpaths =
for(dep, privdep): \
rpaths += $$eval(QT.$${dep}.libs)
QMAKE_RPATHLINKDIR *= $$unique(rpaths)
export(QMAKE_RPATHLINKDIR)
}
# variable, default, [suffix for variable for system() use], [prepare primary variable for system() use]
defineTest(qtPrepareTool) {
cmd = $$eval(QT_TOOL.$${2}.binary)

View File

@ -42,6 +42,8 @@ host_build {
}
}
CONFIG += relative_qt_rpath # Qt libraries should be relocatable
ucmodule = $$upper($$MODULE)
isEmpty(MODULE_INCNAME): MODULE_INCNAME = $$TARGET
@ -185,6 +187,28 @@ equals(QT_ARCH, i386):contains(QT_CPU_FEATURES.$$QT_ARCH, sse2):compiler_support
QMAKE_CXXFLAGS += -mfpmath=sse
}
unix:!isEmpty(QMAKE_LFLAGS_VERSION_SCRIPT):!no_linker_version_script:!static {
verscript = $$OUT_PWD/$${TARGET}.version
QMAKE_LFLAGS += $${QMAKE_LFLAGS_VERSION_SCRIPT}$$verscript
internal_module {
verscript_content = "Qt_$${QT_MAJOR_VERSION}_PRIVATE_API { *; };"
} else {
current = Qt_$$QT_MAJOR_VERSION
verscript_content = "$$current { *; };"
for(i, 0..$$section(VERSION, ., 1, 1)) {
previous = $$current
current = Qt_$${QT_MAJOR_VERSION}.$$i
verscript_content += "$$current {} $$previous;"
}
}
write_file($$verscript, verscript_content)|error("Aborting.")
unset(current)
unset(previous)
unset(verscript)
unset(verscript_content)
}
android: CONFIG += qt_android_deps
#install directives

View File

@ -49,15 +49,6 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
module_libs = "\$\$QT_MODULE_HOST_LIB_BASE"
else: \
module_libs = "\$\$QT_MODULE_LIB_BASE"
unix:!static {
host_build: \
module_rpath = $$[QT_HOST_LIBS]
else: \
module_rpath = $$[QT_INSTALL_LIBS/dev]
module_rpath = "QT.$${MODULE_ID}.rpath = $$val_escape(module_rpath)"
} else {
module_rpath =
}
!isEmpty(QT_PRIVATE): \
module_rundep = "QT.$${MODULE_ID}.run_depends = $$replace(QT_PRIVATE, -private$, _private)"
else: \
@ -115,7 +106,6 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
"" \
"QT.$${MODULE_ID}.name = $$TARGET" \
"QT.$${MODULE_ID}.libs = $$module_libs" \
$$module_rpath \
$$module_master \
"QT.$${MODULE_ID}.includes = $$MODULE_INCLUDES"
!host_build: MODULE_PRI_CONT += \

View File

@ -30,6 +30,8 @@ tool_plugin {
contains(QT_CONFIG, build_all):CONFIG += build_all
}
CONFIG += relative_qt_rpath # Qt's plugins should be relocatable
CONFIG(static, static|shared)|prefix_build {
isEmpty(MODULE): MODULE = $$basename(TARGET)

View File

@ -0,0 +1,12 @@
*msvc2015 {
# Note that the order is important, ucrt(d) has to be first
# Otherwise the linker might use malloc from a different library
# but free_dbg() from the runtime, causing assert when deleting
# items from different heaps
CONFIG(debug, debug|release): \
QMAKE_LIBS = ucrtd.lib $$QMAKE_LIBS
else: \
QMAKE_LIBS = ucrt.lib $$QMAKE_LIBS
}
load(default_pre)

View File

@ -58,9 +58,11 @@
VCLIBS = Microsoft.VCLibs.$$replace(MSVC_VER, \\., ).00
winphone: VCLIBS = $${VCLIBS}.Phone
CONFIG(debug, debug|release): \
WINRT_MANIFEST.dependencies += $${VCLIBS}.Debug
VCLIBS = $${VCLIBS}.Debug
else: \
WINRT_MANIFEST.dependencies += $$VCLIBS
VCLIBS = $${VCLIBS}
contains(MSVC_VER, "14.0"): VCLIBS = "$${VCLIBS}\" MinVersion=\"14.0.0.0\" Publisher=\"CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
WINRT_MANIFEST.dependencies += $$VCLIBS
}
# Provide default values for required variables
@ -122,12 +124,11 @@
}
# Dependencies are given as a string list. The CRT dependency is added automatically above.
# For MSVC2015 the dependencies are added in conjunction with TargetDeviceFamily
WINRT_MANIFEST.dependencies = $$unique(WINRT_MANIFEST.dependencies)
!isEmpty(WINRT_MANIFEST.dependencies) {
MANIFEST_DEPENDENCIES += "<Dependencies>"
for(DEPENDENCY, WINRT_MANIFEST.dependencies): \
MANIFEST_DEPENDENCIES += " <PackageDependency Name=\"$$DEPENDENCY\" />"
MANIFEST_DEPENDENCIES += "</Dependencies>"
WINRT_MANIFEST.dependencies = $$join(MANIFEST_DEPENDENCIES, $$INDENT, $$INDENT)
}
@ -159,5 +160,13 @@
WINRT_MANIFEST.$${ICON_NAME} = assets/$$basename(ICON_FILE)
}
!contains(TEMPLATE, "vc.*") {
winrt_manifest_install.files = $$manifest_file.output
winrt_manifest_install.path = $$target.path
winrt_assets_install.files = $$BUILD_DIR/assets/*
winrt_assets_install.path = $$target.path/assets
INSTALLS += winrt_manifest_install winrt_assets_install
}
QMAKE_SUBSTITUTES += manifest_file
}

View File

@ -21,11 +21,11 @@
!yacc_no_name_mangle:QMAKE_YACCDECLFLAGS += $$QMAKE_YACCFLAGS_MANGLE
yacc_decl.commands = \
-$(DEL_FILE) $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t) \
-$(DEL_FILE) $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_H)} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t) \
$$QMAKE_YACC $$QMAKE_YACCDECLFLAGS ${QMAKE_FILE_IN}$$escape_expand(\\n\\t) \
$(MOVE) $${QMAKE_YACC_HEADER} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)}$$escape_expand(\\n\\t) \
$(MOVE) $${QMAKE_YACC_SOURCE} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t)
yacc_decl.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)}
$(MOVE) $${QMAKE_YACC_HEADER} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_H)}$$escape_expand(\\n\\t) \
$(MOVE) $${QMAKE_YACC_SOURCE} $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_CPP)}$$escape_expand(\\n\\t)
yacc_decl.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_H)}
silent:yacc_decl.commands = @echo Yacc ${QMAKE_FILE_IN} && $$yacc_decl.commands
QMAKE_EXTRA_COMPILERS += yacc_decl
@ -36,7 +36,7 @@
yacc_impl.input = YACCSOURCES
yacc_impl.variable_out = GENERATED_SOURCES
yacc_impl.commands = $$escape_expand(\\n) # We don't want any commands where, but if command is empty no rules are created
yacc_impl.depends = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_H)} # Make sure we depend on the step above
yacc_impl.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}_yacc$${first(QMAKE_EXT_CPP)} # Faked output from this step, output really created in step above
yacc_impl.depends = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_H)} # Make sure we depend on the step above
yacc_impl.output = $${QMAKE_CPP_MOD_MOC}${QMAKE_FILE_BASE}$${QMAKE_MOD_YACC}$${first(QMAKE_EXT_CPP)} # Faked output from this step, output really created in step above
QMAKE_EXTRA_COMPILERS += yacc_impl
}

View File

@ -18,13 +18,15 @@ QMAKE_CFLAGS_WARN_ON = -w1 -Wall -Wcheck -wd1572,873,2259,2261
QMAKE_CFLAGS_WARN_OFF = -w
QMAKE_CFLAGS_RELEASE = -O2 -falign-functions=16 -ansi-alias -fstrict-aliasing
QMAKE_CFLAGS_DEBUG = -O0 -g
QMAKE_CFLAGS_SHLIB = -fPIC -fno-jump-tables
QMAKE_CFLAGS_SHLIB = -fPIC
QMAKE_CFLAGS_STATIC_LIB = $$QMAKE_CFLAGS_SHLIB
QMAKE_CFLAGS_YACC =
QMAKE_CFLAGS_ISYSTEM = -isystem
QMAKE_CFLAGS_THREAD = -D_REENTRANT
QMAKE_CFLAGS_SPLIT_SECTIONS = -ffunction-sections
QMAKE_CFLAGS_LTCG = -ipo
QMAKE_CFLAGS_LTCG = -ipo -fno-fat-lto-objects
QMAKE_CFLAGS_LTCG_FATOBJECTS = -ffat-lto-objects
QMAKE_CFLAGS_DISABLE_LTCG = -no-ipo
QMAKE_CFLAGS_SSE2 += -xSSE2
QMAKE_CFLAGS_SSE3 += -xSSE3
@ -50,8 +52,14 @@ QMAKE_CXXFLAGS_SPLIT_SECTIONS = $$QMAKE_CFLAGS_SPLIT_SECTIONS
# Disabling exceptions disabled - workaround for QTBUG-36577
#QMAKE_CXXFLAGS_EXCEPTIONS_OFF = -fno-exceptions
QMAKE_CXXFLAGS_CXX11 = -std=c++0x
QMAKE_CXXFLAGS_CXX14 = -std=c++1y
QMAKE_CXXFLAGS_CXX1Z = -std=c++1z
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++0x
QMAKE_CXXFLAGS_GNUCXX14 = -std=gnu++1y
QMAKE_CXXFLAGS_GNUCXX1Z = -std=gnu++1z
QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
QMAKE_CXXFLAGS_LTCG_FATOBJECTS = $$QMAKE_CFLAGS_LTCG_FATOBJECTS
QMAKE_CXXFLAGS_DISABLE_LTCG = $$QMAKE_CFLAGS_DISABLE_LTCG
QMAKE_INCDIR =
QMAKE_LIBDIR =
@ -73,6 +81,8 @@ QMAKE_LFLAGS_NOUNDEF = -Wl,-z,defs
QMAKE_LFLAGS_RPATH = -Wl,-rpath,
QMAKE_LFLAGS_RPATHLINK = -Wl,-rpath-link,
QMAKE_LFLAGS_CXX11 =
QMAKE_LFLAGS_CXX14 =
QMAKE_LFLAGS_CXX1Z =
QMAKE_LFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
QMAKE_LIBS =
@ -98,6 +108,7 @@ QMAKE_CXXFLAGS_PRECOMPILE = -c -pch-create ${QMAKE_PCH_OUTPUT} -include ${QMAKE_
# -Bsymbolic-functions (ld) support
QMAKE_LFLAGS_BSYMBOLIC_FUNC = -Wl,-Bsymbolic-functions
QMAKE_LFLAGS_DYNAMIC_LIST = -Wl,--dynamic-list,
QMAKE_LFLAGS_VERSION_SCRIPT = -Wl,--version-script,
# Symbol visibility control
QMAKE_CFLAGS_HIDESYMS += -fvisibility=hidden

View File

@ -18,12 +18,13 @@ QMAKE_CFLAGS_WARN_ON = -w1 -Wcheck -wd654,1572,411,873,1125,2259,2261,3280
QMAKE_CFLAGS_WARN_OFF = -w
QMAKE_CFLAGS_RELEASE =
QMAKE_CFLAGS_DEBUG = -g
QMAKE_CFLAGS_SHLIB = -fPIC -fno-jump-tables
QMAKE_CFLAGS_SHLIB = -fPIC
QMAKE_CFLAGS_STATIC_LIB = $$QMAKE_CFLAGS_SHLIB
QMAKE_CFLAGS_YACC = -Wno-unused -Wno-parentheses
QMAKE_CFLAGS_THREAD =
QMAKE_CFLAGS_SPLIT_SECTIONS = -ffunction-sections
QMAKE_CFLAGS_LTCG = -ipo
QMAKE_CFLAGS_DISABLE_LTCG = -no-ipo
QMAKE_CFLAGS_SSE2 += -msse2
QMAKE_CFLAGS_SSE3 += -msse3
@ -53,9 +54,14 @@ QMAKE_CXXFLAGS_STATIC_LIB = $$QMAKE_CFLAGS_STATIC_LIB
QMAKE_CXXFLAGS_YACC = $$QMAKE_CFLAGS_YACC
QMAKE_CXXFLAGS_THREAD = $$QMAKE_CFLAGS_THREAD
QMAKE_CXXFLAGS_CXX11 = -std=c++11
QMAKE_CXXFLAGS_CXX14 = -std=c++1y
QMAKE_CXXFLAGS_CXX1Z = -std=c++1z
QMAKE_CXXFLAGS_GNUCXX11 = -std=gnu++11
QMAKE_CXXFLAGS_GNUCXX14 = -std=gnu++1y
QMAKE_CXXFLAGS_GNUCXX1Z = -std=gnu++1z
QMAKE_CXXFLAGS_SPLIT_SECTIONS = $$QMAKE_CFLAGS_SPLIT_SECTIONS
QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG
QMAKE_CXXFLAGS_DISABLE_LTCG = $$QMAKE_CFLAGS_DISABLE_LTCG
QMAKE_LINK = icpc
QMAKE_LINK_SHLIB = icpc

View File

@ -33,7 +33,7 @@
##
#############################################################################
booted_simulator=$(xcrun simctl list devices | grep -v unavailable | grep Booted | perl -lne 'print $1 if /\((.*?)\)/')
booted_simulator=$(xcrun simctl list devices | grep -E "iPhone|iPad" | grep -v unavailable | grep Booted | perl -lne 'print $1 if /\((.*?)\)/')
echo "IPHONESIMULATOR_DEVICES = $booted_simulator"
xcodebuild test -scheme $1 -destination 'id=0' -destination-timeout 1 2>&1| sed -n 's/{ \(platform:.*\) }/\1/p' | while read destination; do

View File

@ -67,7 +67,7 @@ endif
%-iphoneos: DEVICES = $(IPHONEOS_DEVICES)
IPHONEOS_GENERIC_DESTINATION := "generic/platform=iOS"
IPHONESIMULATOR_GENERIC_DESTINATION := "id=$(shell xcrun simctl list devices | grep -v unavailable | perl -lne 'print $$1 if /\((.*?)\)/' | tail -n 1)"
IPHONESIMULATOR_GENERIC_DESTINATION := "id=$(shell xcrun simctl list devices | grep -E 'iPhone|iPad' | grep -v unavailable | perl -lne 'print $$1 if /\((.*?)\)/' | tail -n 1)"
DESTINATION = $(if $(DESTINATION_ID),"id=$(DESTINATION_ID)",$(value $(call toupper,$(call basesdk,$(SDK)))_GENERIC_DESTINATION))

View File

@ -71,6 +71,7 @@ QMAKE_PCH_OUTPUT_EXT = .gch
# -Bsymbolic-functions (ld) support
QMAKE_LFLAGS_BSYMBOLIC_FUNC = -Wl,-Bsymbolic-functions
QMAKE_LFLAGS_DYNAMIC_LIST = -Wl,--dynamic-list,
QMAKE_LFLAGS_VERSION_SCRIPT = -Wl,--version-script,
#
# qmake configuration for common linux

Some files were not shown because too many files have changed in this diff Show More