From c530ca1c170798159c3d84029841a1224d1cdc65 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 3 Mar 2019 12:14:43 +0100 Subject: QLineF: add intersects() as a replacement for intersect() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QLineF::intersect() does not follow the naming rules for functions. Therefore add a replacement function intersects() instead and also rename the return type from IntersectType to IntersectionType [ChangeLog][QtCore][QLineF] added QLineF::intersects() as a replacement for QLineF::intersect() Change-Id: I744b960ea339cb817facb12f296f78cca3e7d938 Reviewed-by: Jędrzej Nowacki Reviewed-by: Konstantin Shegunov --- examples/widgets/graphicsview/diagramscene/arrow.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'examples') diff --git a/examples/widgets/graphicsview/diagramscene/arrow.cpp b/examples/widgets/graphicsview/diagramscene/arrow.cpp index 88160d9399..525e0b3fbb 100644 --- a/examples/widgets/graphicsview/diagramscene/arrow.cpp +++ b/examples/widgets/graphicsview/diagramscene/arrow.cpp @@ -113,15 +113,13 @@ void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QLineF centerLine(myStartItem->pos(), myEndItem->pos()); QPolygonF endPolygon = myEndItem->polygon(); QPointF p1 = endPolygon.first() + myEndItem->pos(); - QPointF p2; QPointF intersectPoint; - QLineF polyLine; for (int i = 1; i < endPolygon.count(); ++i) { - p2 = endPolygon.at(i) + myEndItem->pos(); - polyLine = QLineF(p1, p2); - QLineF::IntersectType intersectType = - polyLine.intersect(centerLine, &intersectPoint); - if (intersectType == QLineF::BoundedIntersection) + QPointF p2 = endPolygon.at(i) + myEndItem->pos(); + QLineF polyLine = QLineF(p1, p2); + QLineF::IntersectionType intersectionType = + polyLine.intersects(centerLine, &intersectPoint); + if (intersectionType == QLineF::BoundedIntersection) break; p1 = p2; } -- cgit v1.2.3 From 8e2895557471538afc4610c4340701a39d59a851 Mon Sep 17 00:00:00 2001 From: Jesus Fernandez Date: Tue, 2 Oct 2018 11:44:49 +0200 Subject: Plug and paint example: Fix -Wweak-tables Fixes warning: 'BrushInterface' has no out-of-line virtual method definitions; its vtable will be emitted in every translation unit Change-Id: I2e693ac60e9eba1976665546e1c9c4a92e6ff63b Reviewed-by: Paul Wicking Reviewed-by: Richard Moe Gustavsen --- examples/widgets/tools/plugandpaint/app/interfaces.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/widgets/tools/plugandpaint/app/interfaces.h b/examples/widgets/tools/plugandpaint/app/interfaces.h index a1e91e13ff..705e578809 100644 --- a/examples/widgets/tools/plugandpaint/app/interfaces.h +++ b/examples/widgets/tools/plugandpaint/app/interfaces.h @@ -68,7 +68,7 @@ QT_END_NAMESPACE class BrushInterface { public: - virtual ~BrushInterface() {} + virtual ~BrushInterface() = default; virtual QStringList brushes() const = 0; virtual QRect mousePress(const QString &brush, QPainter &painter, @@ -84,7 +84,7 @@ public: class ShapeInterface { public: - virtual ~ShapeInterface() {} + virtual ~ShapeInterface() = default; virtual QStringList shapes() const = 0; virtual QPainterPath generateShape(const QString &shape, @@ -96,7 +96,7 @@ public: class FilterInterface { public: - virtual ~FilterInterface() {} + virtual ~FilterInterface() = default; virtual QStringList filters() const = 0; virtual QImage filterImage(const QString &filter, const QImage &image, -- cgit v1.2.3 From 9ec564b0bfc94c2d33f02b24ca081b64ff9ebb9b Mon Sep 17 00:00:00 2001 From: James McDonnell Date: Fri, 4 May 2018 14:23:51 -0400 Subject: Basic foreign window support for QNX Requires a screen with working context permission parsing. Currently, all context permission requests fail because the parsing is incorrect. A context permission is added temporarily to prevent CLOSE/CREATE events when Qt reparents foreign windows. Qt does this temporarily when a foreign window is wrapped in a widget. Change-Id: I84c18e70d43239286fcd53715332d7015cf1a826 Reviewed-by: Rafael Roquetto --- examples/widgets/qnx/foreignwindows/collector.cpp | 176 +++++++++++++++++++++ examples/widgets/qnx/foreignwindows/collector.h | 75 +++++++++ .../widgets/qnx/foreignwindows/foreignwindows.pro | 11 ++ examples/widgets/qnx/foreignwindows/main.cpp | 53 +++++++ 4 files changed, 315 insertions(+) create mode 100644 examples/widgets/qnx/foreignwindows/collector.cpp create mode 100644 examples/widgets/qnx/foreignwindows/collector.h create mode 100644 examples/widgets/qnx/foreignwindows/foreignwindows.pro create mode 100644 examples/widgets/qnx/foreignwindows/main.cpp (limited to 'examples') diff --git a/examples/widgets/qnx/foreignwindows/collector.cpp b/examples/widgets/qnx/foreignwindows/collector.cpp new file mode 100644 index 0000000000..4b9e774945 --- /dev/null +++ b/examples/widgets/qnx/foreignwindows/collector.cpp @@ -0,0 +1,176 @@ +/*************************************************************************** +** +** Copyright (C) 2018 QNX Software Systems. All rights reserved. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include + +#include +#include + +#include "collector.h" + +constexpr int MANAGER_EVENT_NAME_SUGGESTION = 9999; + +Collector::Collector(QWidget *parent) + : QWidget(parent) +{ + QApplication::instance()->installNativeEventFilter(this); + + QLayout *layout = new QHBoxLayout(this); + setLayout(layout); +} + +Collector::~Collector() +{ + QApplication::instance()->removeNativeEventFilter(this); +} + +bool Collector::nativeEventFilter(const QByteArray &eventType, void *message, long *result) +{ + Q_UNUSED(result); + + if (eventType == QByteArrayLiteral("screen_event_t")) + return filterQnxScreenEvent(static_cast(message)); + + return false; +} + +bool Collector::filterQnxScreenEvent(screen_event_t event) +{ + int objectType = SCREEN_OBJECT_TYPE_CONTEXT; + screen_get_event_property_iv(event, SCREEN_PROPERTY_OBJECT_TYPE, &objectType); + + if (objectType == SCREEN_OBJECT_TYPE_WINDOW) + return filterQnxScreenWindowEvent(event); + + return false; +} + +bool Collector::filterQnxScreenWindowEvent(screen_event_t event) +{ + int eventType = SCREEN_EVENT_NONE; + screen_get_event_property_iv(event, SCREEN_PROPERTY_TYPE, &eventType); + screen_window_t window = nullptr; + screen_get_event_property_pv(event, + SCREEN_PROPERTY_WINDOW, + reinterpret_cast(&window)); + + if (eventType == SCREEN_EVENT_CREATE) + return filterQnxScreenWindowCreateEvent(window, event); + else if (eventType == SCREEN_EVENT_CLOSE) + return filterQnxScreenWindowCloseEvent(window, event); + else if (eventType == SCREEN_EVENT_MANAGER) + return filterQnxScreenWindowManagerEvent(window, event); + + return false; +} + +bool Collector::filterQnxScreenWindowCreateEvent(screen_window_t window, screen_event_t event) +{ + Q_UNUSED(event); + WId winId = reinterpret_cast(window); + + QByteArray parentGroup(256, 0); + screen_get_window_property_cv(window, + SCREEN_PROPERTY_PARENT, + parentGroup.length(), + parentGroup.data()); + parentGroup.resize(strlen(parentGroup.constData())); + + QByteArray group(256, 0); + screen_get_window_property_cv(reinterpret_cast(windowHandle()->winId()), + SCREEN_PROPERTY_GROUP, + group.length(), + group.data()); + group.resize(strlen(group.constData())); + + if (parentGroup != group) + return false; + + Collectible collectible; + collectible.window = QWindow::fromWinId(winId); + collectible.widget = QWidget::createWindowContainer(collectible.window, this); + layout()->addWidget(collectible.widget); + m_collectibles.append(collectible); + + return false; +} + +bool Collector::filterQnxScreenWindowCloseEvent(screen_window_t window, screen_event_t event) +{ + Q_UNUSED(event); + WId winId = reinterpret_cast(window); + auto it = std::find_if(m_collectibles.begin(), m_collectibles.end(), + [winId] (const Collectible &collectible) { + return collectible.window->winId() == winId; + }); + if (it != m_collectibles.end()) { + delete it->widget; + // it->window is deleted by it->widget. + m_collectibles.erase(it); + } + + return false; +} + +bool Collector::filterQnxScreenWindowManagerEvent(screen_window_t window, screen_event_t event) +{ + int managerEventType = 0; + screen_get_event_property_iv(event, SCREEN_PROPERTY_SUBTYPE, &managerEventType); + + if (managerEventType == MANAGER_EVENT_NAME_SUGGESTION) + return filterQnxScreenWindowManagerNameEvent(window, event); + + return false; +} + +bool Collector::filterQnxScreenWindowManagerNameEvent(screen_window_t window, screen_event_t event) +{ + Q_UNUSED(window); + int dataSize = 0; + screen_get_event_property_iv(event, SCREEN_PROPERTY_SIZE, &dataSize); + if (dataSize > 0) { + QByteArray data(dataSize, 0); + screen_get_event_property_cv(event, SCREEN_PROPERTY_USER_DATA, data.size(), data.data()); + } + + return false; +} diff --git a/examples/widgets/qnx/foreignwindows/collector.h b/examples/widgets/qnx/foreignwindows/collector.h new file mode 100644 index 0000000000..2b1ed499ff --- /dev/null +++ b/examples/widgets/qnx/foreignwindows/collector.h @@ -0,0 +1,75 @@ +/*************************************************************************** +** +** Copyright (C) 2018 QNX Software Systems. All rights reserved. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef COLLECTOR_H_ +#define COLLECTOR_H_ + +#include +#include +#include + +#include + +class Collector : public QWidget, public QAbstractNativeEventFilter +{ +public: + explicit Collector(QWidget *parent = nullptr); + ~Collector() override; + + bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override; + +private: + struct Collectible + { + QWindow *window; + QWidget *widget; + }; + QVector m_collectibles; + + bool filterQnxScreenEvent(screen_event_t event); + bool filterQnxScreenWindowEvent(screen_event_t event); + bool filterQnxScreenWindowCreateEvent(screen_window_t window, screen_event_t event); + bool filterQnxScreenWindowCloseEvent(screen_window_t window, screen_event_t event); + bool filterQnxScreenWindowManagerEvent(screen_window_t window, screen_event_t event); + bool filterQnxScreenWindowManagerNameEvent(screen_window_t window, + screen_event_t event); +}; + + +#endif /* COLLECTOR_H_ */ diff --git a/examples/widgets/qnx/foreignwindows/foreignwindows.pro b/examples/widgets/qnx/foreignwindows/foreignwindows.pro new file mode 100644 index 0000000000..09ff8633eb --- /dev/null +++ b/examples/widgets/qnx/foreignwindows/foreignwindows.pro @@ -0,0 +1,11 @@ +TEMPLATE = app + +HEADERS += collector.h +SOURCES += main.cpp collector.cpp +LIBS += -lscreen + +QT += widgets + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/widgets/qnx/foreignwindows +INSTALLS += target diff --git a/examples/widgets/qnx/foreignwindows/main.cpp b/examples/widgets/qnx/foreignwindows/main.cpp new file mode 100644 index 0000000000..128e93cf88 --- /dev/null +++ b/examples/widgets/qnx/foreignwindows/main.cpp @@ -0,0 +1,53 @@ +/*************************************************************************** +** +** Copyright (C) 2018 QNX Software Systems. All rights reserved. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the plugins of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "collector.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + Collector collector; + collector.resize(640, 480); + collector.show(); + + return app.exec(); +} -- cgit v1.2.3 From deae75ae093d11714dd2f05a40dcfcdb6bb8e10e Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Mon, 18 Dec 2017 11:28:33 +0100 Subject: TextEdit example: add Markdown as a supported format Also use QT_CONFIG to disable features gracefully if Qt is configured without them. Change-Id: I38e92bf5fd70f77fc4d5158769d590619be8905f Reviewed-by: Gatis Paeglis --- examples/widgets/richtext/textedit/example.md | 96 +++++++++++++++++++++++++ examples/widgets/richtext/textedit/textedit.cpp | 33 +++++++-- 2 files changed, 125 insertions(+), 4 deletions(-) create mode 100644 examples/widgets/richtext/textedit/example.md (limited to 'examples') diff --git a/examples/widgets/richtext/textedit/example.md b/examples/widgets/richtext/textedit/example.md new file mode 100644 index 0000000000..70aeaf7649 --- /dev/null +++ b/examples/widgets/richtext/textedit/example.md @@ -0,0 +1,96 @@ +# QTextEdit + +The QTextEdit widget is an advanced editor that supports formatted rich text. +It can be used to display HTML and other rich document formats. Internally, +QTextEdit uses the QTextDocument class to describe both the high-level +structure of each document and the low-level formatting of paragraphs. + +If you are viewing this document in the textedit example, you can edit this +document to explore Qt's rich text editing features. We have included some +comments in each of the following sections to encourage you to experiment. + +## Font and Paragraph Styles + +QTextEdit supports **bold**, *italic*, & ~~strikethrough~~ font styles, and +can display multicolored text. Font families such as Times New Roman and `Courier` +can also be used directly. *If you place the cursor in a region of styled text, +the controls in the tool bars will change to reflect the current style.* + +Paragraphs can be formatted so that the text is left-aligned, right-aligned, +centered, or fully justified. + +*Try changing the alignment of some text and resize the editor to see how the +text layout changes.* + +## Lists + +Different kinds of lists can be included in rich text documents. Standard +bullet lists can be nested, using different symbols for each level of the list: + +- Disc symbols are typically used for top-level list items. + * Circle symbols can be used to distinguish between items in lower-level + lists. + + Square symbols provide a reasonable alternative to discs and circles. + +Ordered lists can be created that can be used for tables of contents. Different +characters can be used to enumerate items, and we can use both Roman and Arabic +numerals in the same list structure: + +1. Introduction +2. Qt Tools + 1) Qt Assistant + 2) Qt Designer + 1. Form Editor + 2. Component Architecture + 3) Qt Linguist + +The list will automatically be renumbered if you add or remove items. *Try +adding new sections to the above list or removing existing item to see the +numbers change.* + +## Images + +Inline images are treated like ordinary ranges of characters in the text +editor, so they flow with the surrounding text. Images can also be selected in +the same way as text, making it easy to cut, copy, and paste them. + +![logo](images/logo32.png "logo") *Try to select this image by clicking and +dragging over it with the mouse, or use the text cursor to select it by holding +down Shift and using the arrow keys. You can then cut or copy it, and paste it +into different parts of this document.* + +## Tables + +QTextEdit can arrange and format tables, supporting features such as row and +column spans, text formatting within cells, and size constraints for columns. + +| | Development Tools | Programming Techniques | Graphical User Interfaces | +| ------------: | ----------------- | ---------------------- | ------------------------- | +| 9:00 - 11:00 | Introduction to Qt ||| +| 11:00 - 13:00 | Using qmake | Object-oriented Programming | Layouts in Qt | +| 13:00 - 15:00 | Qt Designer Tutorial | Extreme Programming | Writing Custom Styles | +| 15:00 - 17:00 | Qt Linguist and Internationalization |   |   | + +*Try adding text to the cells in the table and experiment with the alignment of +the paragraphs.* + +## Hyperlinks + +QTextEdit is designed to support hyperlinks between documents, and this feature +is used extensively in +[Qt Assistant](http://doc.qt.io/qt-5/qtassistant-index.html). Hyperlinks are +automatically created when an HTML file is imported into an editor. Since the +rich text framework supports hyperlinks natively, they can also be created +programatically. + +## Undo and Redo + +Full support for undo and redo operations is built into QTextEdit and the +underlying rich text framework. Operations on a document can be packaged +together to make editing a more comfortable experience for the user. + +*Try making changes to this document and press `Ctrl+Z` to undo them. You can +always recover the original contents of the document.* + diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp index 3ad9f48b67..7b8c242cfc 100644 --- a/examples/widgets/richtext/textedit/textedit.cpp +++ b/examples/widgets/richtext/textedit/textedit.cpp @@ -71,6 +71,7 @@ #include #include #include +#include #if defined(QT_PRINTSUPPORT_LIB) #include #if QT_CONFIG(printer) @@ -395,11 +396,18 @@ bool TextEdit::load(const QString &f) QByteArray data = file.readAll(); QTextCodec *codec = Qt::codecForHtml(data); QString str = codec->toUnicode(data); + QUrl baseUrl = (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename); + textEdit->document()->setBaseUrl(baseUrl); if (Qt::mightBeRichText(str)) { textEdit->setHtml(str); } else { - str = QString::fromLocal8Bit(data); - textEdit->setPlainText(str); +#if QT_CONFIG(textmarkdownreader) + QMimeDatabase db; + if (db.mimeTypeForFileNameAndData(f, data).name() == QLatin1String("text/markdown")) + textEdit->setMarkdown(str); + else +#endif + textEdit->setPlainText(QString::fromLocal8Bit(data)); } setCurrentFileName(f); @@ -451,7 +459,15 @@ void TextEdit::fileOpen() QFileDialog fileDialog(this, tr("Open File...")); fileDialog.setAcceptMode(QFileDialog::AcceptOpen); fileDialog.setFileMode(QFileDialog::ExistingFile); - fileDialog.setMimeTypeFilters(QStringList() << "text/html" << "text/plain"); + fileDialog.setMimeTypeFilters(QStringList() +#if QT_CONFIG(texthtmlparser) + << "text/html" +#endif +#if QT_CONFIG(textmarkdownreader) + + << "text/markdown" +#endif + << "text/plain"); if (fileDialog.exec() != QDialog::Accepted) return; const QString fn = fileDialog.selectedFiles().first(); @@ -485,9 +501,18 @@ bool TextEdit::fileSaveAs() QFileDialog fileDialog(this, tr("Save as...")); fileDialog.setAcceptMode(QFileDialog::AcceptSave); QStringList mimeTypes; - mimeTypes << "application/vnd.oasis.opendocument.text" << "text/html" << "text/plain"; + mimeTypes << "text/plain" +#if QT_CONFIG(textodfwriter) + << "application/vnd.oasis.opendocument.text" +#endif +#if QT_CONFIG(textmarkdownwriter) + << "text/markdown" +#endif + << "text/html"; fileDialog.setMimeTypeFilters(mimeTypes); +#if QT_CONFIG(textodfwriter) fileDialog.setDefaultSuffix("odt"); +#endif if (fileDialog.exec() != QDialog::Accepted) return false; const QString fn = fileDialog.selectedFiles().first(); -- cgit v1.2.3 From 75256d62d2462103180b368aa79b933acf71f444 Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Wed, 6 Feb 2019 17:10:42 +0100 Subject: Render markdown task lists (checkboxes instead of bullets) in QTextEdit Checkboxes are right-aligned with any bullets that are in the same QTextList so that there is enough space to make them larger than bullets. But hopefully mixing bullets and checkboxes will be a rarely-used feature. Change-Id: I28e274d1f7883aa093df29eb4988e99641e87a71 Reviewed-by: Gatis Paeglis --- examples/widgets/richtext/textedit/example.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'examples') diff --git a/examples/widgets/richtext/textedit/example.md b/examples/widgets/richtext/textedit/example.md index 70aeaf7649..a16a9197b4 100644 --- a/examples/widgets/richtext/textedit/example.md +++ b/examples/widgets/richtext/textedit/example.md @@ -50,6 +50,12 @@ The list will automatically be renumbered if you add or remove items. *Try adding new sections to the above list or removing existing item to see the numbers change.* +Task lists can be used to track progress on projects: + +- [ ] This is not yet done +- This is just a bullet point +- [x] This is done + ## Images Inline images are treated like ordinary ranges of characters in the text -- cgit v1.2.3 From 0df30ff22e50aa301791fc72f106ab15ce385a6a Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Mon, 18 Feb 2019 15:40:04 +0100 Subject: Add task list checkbox manipulation features to the TextEdit example Change-Id: I5f0b8cb94d1af609ec531f9765d58be65b1129a3 Reviewed-by: Gatis Paeglis --- .../textedit/images/mac/checkbox-checked.png | Bin 0 -> 1167 bytes .../richtext/textedit/images/mac/checkbox.png | Bin 0 -> 779 bytes .../textedit/images/win/checkbox-checked.png | Bin 0 -> 1167 bytes .../richtext/textedit/images/win/checkbox.png | Bin 0 -> 779 bytes examples/widgets/richtext/textedit/textedit.cpp | 64 ++++++++++++++++++--- examples/widgets/richtext/textedit/textedit.h | 2 + examples/widgets/richtext/textedit/textedit.qrc | 4 ++ 7 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 examples/widgets/richtext/textedit/images/mac/checkbox-checked.png create mode 100644 examples/widgets/richtext/textedit/images/mac/checkbox.png create mode 100644 examples/widgets/richtext/textedit/images/win/checkbox-checked.png create mode 100644 examples/widgets/richtext/textedit/images/win/checkbox.png (limited to 'examples') diff --git a/examples/widgets/richtext/textedit/images/mac/checkbox-checked.png b/examples/widgets/richtext/textedit/images/mac/checkbox-checked.png new file mode 100644 index 0000000000..a072d7fb5c Binary files /dev/null and b/examples/widgets/richtext/textedit/images/mac/checkbox-checked.png differ diff --git a/examples/widgets/richtext/textedit/images/mac/checkbox.png b/examples/widgets/richtext/textedit/images/mac/checkbox.png new file mode 100644 index 0000000000..4064909712 Binary files /dev/null and b/examples/widgets/richtext/textedit/images/mac/checkbox.png differ diff --git a/examples/widgets/richtext/textedit/images/win/checkbox-checked.png b/examples/widgets/richtext/textedit/images/win/checkbox-checked.png new file mode 100644 index 0000000000..a072d7fb5c Binary files /dev/null and b/examples/widgets/richtext/textedit/images/win/checkbox-checked.png differ diff --git a/examples/widgets/richtext/textedit/images/win/checkbox.png b/examples/widgets/richtext/textedit/images/win/checkbox.png new file mode 100644 index 0000000000..4064909712 Binary files /dev/null and b/examples/widgets/richtext/textedit/images/win/checkbox.png differ diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp index 7b8c242cfc..683e441fce 100644 --- a/examples/widgets/richtext/textedit/textedit.cpp +++ b/examples/widgets/richtext/textedit/textedit.cpp @@ -343,6 +343,15 @@ void TextEdit::setupTextActions() actionTextColor = menu->addAction(pix, tr("&Color..."), this, &TextEdit::textColor); tb->addAction(actionTextColor); + menu->addSeparator(); + + const QIcon checkboxIcon = QIcon::fromTheme("status-checkbox-checked", QIcon(rsrcPath + "/checkbox-checked.png")); + actionToggleCheckState = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &TextEdit::setChecked); + actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K); + actionToggleCheckState->setCheckable(true); + actionToggleCheckState->setPriority(QAction::LowPriority); + tb->addAction(actionToggleCheckState); + tb = addToolBar(tr("Format Actions")); tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); addToolBarBreak(Qt::TopToolBarArea); @@ -354,6 +363,8 @@ void TextEdit::setupTextActions() comboStyle->addItem("Bullet List (Disc)"); comboStyle->addItem("Bullet List (Circle)"); comboStyle->addItem("Bullet List (Square)"); + comboStyle->addItem("Task List (Unchecked)"); + comboStyle->addItem("Task List (Checked)"); comboStyle->addItem("Ordered List (Decimal)"); comboStyle->addItem("Ordered List (Alpha lower)"); comboStyle->addItem("Ordered List (Alpha upper)"); @@ -617,6 +628,7 @@ void TextEdit::textStyle(int styleIndex) { QTextCursor cursor = textEdit->textCursor(); QTextListFormat::Style style = QTextListFormat::ListStyleUndefined; + QTextBlockFormat::MarkerType marker = QTextBlockFormat::NoMarker; switch (styleIndex) { case 1: @@ -629,18 +641,32 @@ void TextEdit::textStyle(int styleIndex) style = QTextListFormat::ListSquare; break; case 4: - style = QTextListFormat::ListDecimal; + if (cursor.currentList()) + style = cursor.currentList()->format().style(); + else + style = QTextListFormat::ListDisc; + marker = QTextBlockFormat::Unchecked; break; case 5: - style = QTextListFormat::ListLowerAlpha; + if (cursor.currentList()) + style = cursor.currentList()->format().style(); + else + style = QTextListFormat::ListDisc; + marker = QTextBlockFormat::Checked; break; case 6: - style = QTextListFormat::ListUpperAlpha; + style = QTextListFormat::ListDecimal; break; case 7: - style = QTextListFormat::ListLowerRoman; + style = QTextListFormat::ListLowerAlpha; break; case 8: + style = QTextListFormat::ListUpperAlpha; + break; + case 9: + style = QTextListFormat::ListLowerRoman; + break; + case 10: style = QTextListFormat::ListUpperRoman; break; default: @@ -665,6 +691,8 @@ void TextEdit::textStyle(int styleIndex) cursor.mergeCharFormat(fmt); textEdit->mergeCurrentCharFormat(fmt); } else { + blockFmt.setMarker(marker); + cursor.setBlockFormat(blockFmt); QTextListFormat listFmt; if (cursor.currentList()) { listFmt = cursor.currentList()->format(); @@ -703,6 +731,11 @@ void TextEdit::textAlign(QAction *a) textEdit->setAlignment(Qt::AlignJustify); } +void TextEdit::setChecked(bool checked) +{ + textStyle(checked ? 5 : 4); +} + void TextEdit::currentCharFormatChanged(const QTextCharFormat &format) { fontChanged(format.font()); @@ -725,24 +758,37 @@ void TextEdit::cursorPositionChanged() comboStyle->setCurrentIndex(3); break; case QTextListFormat::ListDecimal: - comboStyle->setCurrentIndex(4); + comboStyle->setCurrentIndex(6); break; case QTextListFormat::ListLowerAlpha: - comboStyle->setCurrentIndex(5); + comboStyle->setCurrentIndex(7); break; case QTextListFormat::ListUpperAlpha: - comboStyle->setCurrentIndex(6); + comboStyle->setCurrentIndex(8); break; case QTextListFormat::ListLowerRoman: - comboStyle->setCurrentIndex(7); + comboStyle->setCurrentIndex(9); break; case QTextListFormat::ListUpperRoman: - comboStyle->setCurrentIndex(8); + comboStyle->setCurrentIndex(10); break; default: comboStyle->setCurrentIndex(-1); break; } + switch (textEdit->textCursor().block().blockFormat().marker()) { + case QTextBlockFormat::NoMarker: + actionToggleCheckState->setChecked(false); + break; + case QTextBlockFormat::Unchecked: + comboStyle->setCurrentIndex(4); + actionToggleCheckState->setChecked(false); + break; + case QTextBlockFormat::Checked: + comboStyle->setCurrentIndex(5); + actionToggleCheckState->setChecked(true); + break; + } } else { int headingLevel = textEdit->textCursor().blockFormat().headingLevel(); comboStyle->setCurrentIndex(headingLevel ? headingLevel + 8 : 0); diff --git a/examples/widgets/richtext/textedit/textedit.h b/examples/widgets/richtext/textedit/textedit.h index ae0b13a4cc..c253548a4f 100644 --- a/examples/widgets/richtext/textedit/textedit.h +++ b/examples/widgets/richtext/textedit/textedit.h @@ -96,6 +96,7 @@ private slots: void textStyle(int styleIndex); void textColor(); void textAlign(QAction *a); + void setChecked(bool checked); void currentCharFormatChanged(const QTextCharFormat &format); void cursorPositionChanged(); @@ -125,6 +126,7 @@ private: QAction *actionAlignCenter; QAction *actionAlignRight; QAction *actionAlignJustify; + QAction *actionToggleCheckState; QAction *actionUndo; QAction *actionRedo; #ifndef QT_NO_CLIPBOARD diff --git a/examples/widgets/richtext/textedit/textedit.qrc b/examples/widgets/richtext/textedit/textedit.qrc index 7d6efd7d67..8016a07ca0 100644 --- a/examples/widgets/richtext/textedit/textedit.qrc +++ b/examples/widgets/richtext/textedit/textedit.qrc @@ -1,6 +1,8 @@ images/logo32.png + images/mac/checkbox.png + images/mac/checkbox-checked.png images/mac/editcopy.png images/mac/editcut.png images/mac/editpaste.png @@ -20,6 +22,8 @@ images/mac/textunder.png images/mac/zoomin.png images/mac/zoomout.png + images/win/checkbox.png + images/win/checkbox-checked.png images/win/editcopy.png images/win/editcut.png images/win/editpaste.png -- cgit v1.2.3 From 343528841e72adf36a37d9afd7260e260a9342eb Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Tue, 30 Apr 2019 12:51:36 +0200 Subject: Prefix textstream operators with Qt:: As the non prefixed variants are deprecated Change-Id: I2ba09d71b9cea5203b54297a3f2332e6d44fedcf Reviewed-by: Allan Sandfeld Jensen --- .../corelib/serialization/convert/cborconverter.cpp | 2 +- .../corelib/serialization/convert/textconverter.cpp | 6 +++--- examples/xml/htmlinfo/main.cpp | 18 +++++++++--------- 3 files changed, 13 insertions(+), 13 deletions(-) (limited to 'examples') diff --git a/examples/corelib/serialization/convert/cborconverter.cpp b/examples/corelib/serialization/convert/cborconverter.cpp index ad69983eb1..f907bb0af6 100644 --- a/examples/corelib/serialization/convert/cborconverter.cpp +++ b/examples/corelib/serialization/convert/cborconverter.cpp @@ -226,7 +226,7 @@ void CborDiagnosticDumper::saveFile(QIODevice *f, const QVariant &contents, cons QTextStream out(f); out << convertFromVariant(contents, Double).toDiagnosticNotation(opts) - << endl; + << Qt::endl; } CborConverter::CborConverter() diff --git a/examples/corelib/serialization/convert/textconverter.cpp b/examples/corelib/serialization/convert/textconverter.cpp index e80e69a0b5..7aed08f96c 100644 --- a/examples/corelib/serialization/convert/textconverter.cpp +++ b/examples/corelib/serialization/convert/textconverter.cpp @@ -66,7 +66,7 @@ static void dumpVariant(QTextStream &out, const QVariant &v) case QVariant::String: { const QStringList list = v.toStringList(); for (const QString &s : list) - out << s << endl; + out << s << Qt::endl; break; } @@ -80,11 +80,11 @@ static void dumpVariant(QTextStream &out, const QVariant &v) } case QMetaType::Nullptr: - out << "(null)" << endl; + out << "(null)" << Qt::endl; break; default: - out << v.toString() << endl; + out << v.toString() << Qt::endl; break; } } diff --git a/examples/xml/htmlinfo/main.cpp b/examples/xml/htmlinfo/main.cpp index 22bf36f33c..bc19ae4a82 100644 --- a/examples/xml/htmlinfo/main.cpp +++ b/examples/xml/htmlinfo/main.cpp @@ -54,10 +54,10 @@ void parseHtmlFile(QTextStream &out, const QString &fileName) { QFile file(fileName); - out << "Analysis of HTML file: " << fileName << endl; + out << "Analysis of HTML file: " << fileName << Qt::endl; if (!file.open(QIODevice::ReadOnly)) { - out << " Couldn't open the file." << endl << endl << endl; + out << " Couldn't open the file." << Qt::endl << Qt::endl << Qt::endl; return; } @@ -85,22 +85,22 @@ void parseHtmlFile(QTextStream &out, const QString &fileName) //! [2] if (reader.hasError()) { out << " The HTML file isn't well-formed: " << reader.errorString() - << endl << endl << endl; + << Qt::endl << Qt::endl << Qt::endl; return; } //! [2] - out << " Title: \"" << title << '"' << endl - << " Number of paragraphs: " << paragraphCount << endl - << " Number of links: " << links.size() << endl - << " Showing first few links:" << endl; + out << " Title: \"" << title << '"' << Qt::endl + << " Number of paragraphs: " << paragraphCount << Qt::endl + << " Number of links: " << links.size() << Qt::endl + << " Showing first few links:" << Qt::endl; while (links.size() > 5) links.removeLast(); for (const QString &link : qAsConst(links)) - out << " " << link << endl; - out << endl << endl; + out << " " << link << Qt::endl; + out << Qt::endl << Qt::endl; } int main(int argc, char **argv) -- cgit v1.2.3 From d775b1fcb3fc7bd41af37f5d0a4d999320b62364 Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Thu, 4 Apr 2019 18:13:32 +0200 Subject: Remove handling of missing Q_COMPILER_INITIALIZER_LISTS Change-Id: Id65b39c787235a051262544932e6717d076f1ea0 Reviewed-by: Edward Welbourne Reviewed-by: Thiago Macieira --- examples/widgets/widgets/icons/iconpreviewarea.cpp | 40 ---------------------- 1 file changed, 40 deletions(-) (limited to 'examples') diff --git a/examples/widgets/widgets/icons/iconpreviewarea.cpp b/examples/widgets/widgets/icons/iconpreviewarea.cpp index 1a2f514ba8..7a73a137cd 100644 --- a/examples/widgets/widgets/icons/iconpreviewarea.cpp +++ b/examples/widgets/widgets/icons/iconpreviewarea.cpp @@ -79,8 +79,6 @@ IconPreviewArea::IconPreviewArea(QWidget *parent) } //! [0] -#ifdef Q_COMPILER_INITIALIZER_LISTS - //! [42] QVector IconPreviewArea::iconModes() { @@ -107,44 +105,6 @@ QStringList IconPreviewArea::iconStateNames() } //! [42] -#else // Q_COMPILER_INITIALIZER_LISTS - -//! [43] -QVector IconPreviewArea::iconModes() -{ - static QVector result; - if (result.isEmpty()) - result << QIcon::Normal << QIcon::Active << QIcon::Disabled << QIcon::Selected; - return result; -} -//! [43] - -QVector IconPreviewArea::iconStates() -{ - static QVector 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) { -- cgit v1.2.3 From b922c97c9c65ce28f4ea18106f384adf1bbf605a Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Sat, 4 May 2019 08:48:41 +0200 Subject: TextEdit example: add indent/unindent feature It was not possible to interactively create the example text without this feature; and in general it's necessary to work with nested lists. But currently it does not deal with all possible changes of list nesting, because the API seems incomplete for that purpose. Task-number: QTBUG-75589 Change-Id: I3e29ca15a2e7c37300a0103ceb90670716472ffb Reviewed-by: Gatis Paeglis --- .../textedit/images/mac/format-indent-less.png | Bin 0 -> 1201 bytes .../textedit/images/mac/format-indent-more.png | Bin 0 -> 993 bytes .../textedit/images/win/format-indent-less.png | Bin 0 -> 1201 bytes .../textedit/images/win/format-indent-more.png | Bin 0 -> 993 bytes examples/widgets/richtext/textedit/textedit.cpp | 46 +++++++++++++++++++++ examples/widgets/richtext/textedit/textedit.h | 5 +++ examples/widgets/richtext/textedit/textedit.qrc | 4 ++ 7 files changed, 55 insertions(+) create mode 100644 examples/widgets/richtext/textedit/images/mac/format-indent-less.png create mode 100644 examples/widgets/richtext/textedit/images/mac/format-indent-more.png create mode 100644 examples/widgets/richtext/textedit/images/win/format-indent-less.png create mode 100644 examples/widgets/richtext/textedit/images/win/format-indent-more.png (limited to 'examples') diff --git a/examples/widgets/richtext/textedit/images/mac/format-indent-less.png b/examples/widgets/richtext/textedit/images/mac/format-indent-less.png new file mode 100644 index 0000000000..e38074e78b Binary files /dev/null and b/examples/widgets/richtext/textedit/images/mac/format-indent-less.png differ diff --git a/examples/widgets/richtext/textedit/images/mac/format-indent-more.png b/examples/widgets/richtext/textedit/images/mac/format-indent-more.png new file mode 100644 index 0000000000..1bdeabd354 Binary files /dev/null and b/examples/widgets/richtext/textedit/images/mac/format-indent-more.png differ diff --git a/examples/widgets/richtext/textedit/images/win/format-indent-less.png b/examples/widgets/richtext/textedit/images/win/format-indent-less.png new file mode 100644 index 0000000000..e38074e78b Binary files /dev/null and b/examples/widgets/richtext/textedit/images/win/format-indent-less.png differ diff --git a/examples/widgets/richtext/textedit/images/win/format-indent-more.png b/examples/widgets/richtext/textedit/images/win/format-indent-more.png new file mode 100644 index 0000000000..1bdeabd354 Binary files /dev/null and b/examples/widgets/richtext/textedit/images/win/format-indent-more.png differ diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp index 683e441fce..ced77a62ce 100644 --- a/examples/widgets/richtext/textedit/textedit.cpp +++ b/examples/widgets/richtext/textedit/textedit.cpp @@ -317,6 +317,14 @@ void TextEdit::setupTextActions() actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); actionAlignJustify->setCheckable(true); actionAlignJustify->setPriority(QAction::LowPriority); + const QIcon indentMoreIcon = QIcon::fromTheme("format-indent-more", QIcon(rsrcPath + "/format-indent-more.png")); + actionIndentMore = menu->addAction(indentMoreIcon, tr("&Indent"), this, &TextEdit::indent); + actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight); + actionIndentMore->setPriority(QAction::LowPriority); + const QIcon indentLessIcon = QIcon::fromTheme("format-indent-less", QIcon(rsrcPath + "/format-indent-less.png")); + actionIndentLess = menu->addAction(indentLessIcon, tr("&Unindent"), this, &TextEdit::unindent); + actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); + actionIndentLess->setPriority(QAction::LowPriority); // Make sure the alignLeft is always left of the alignRight QActionGroup *alignGroup = new QActionGroup(this); @@ -335,6 +343,10 @@ void TextEdit::setupTextActions() tb->addActions(alignGroup->actions()); menu->addActions(alignGroup->actions()); + tb->addAction(actionIndentMore); + tb->addAction(actionIndentLess); + menu->addAction(actionIndentMore); + menu->addAction(actionIndentLess); menu->addSeparator(); @@ -736,6 +748,40 @@ void TextEdit::setChecked(bool checked) textStyle(checked ? 5 : 4); } +void TextEdit::indent() +{ + modifyIndentation(1); +} + +void TextEdit::unindent() +{ + modifyIndentation(-1); +} + +void TextEdit::modifyIndentation(int amount) +{ + QTextCursor cursor = textEdit->textCursor(); + cursor.beginEditBlock(); + if (cursor.currentList()) { + QTextListFormat listFmt = cursor.currentList()->format(); + // See whether the line above is the list we want to move this item into, + // or whether we need a new list. + QTextCursor above(cursor); + above.movePosition(QTextCursor::Up); + if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) { + above.currentList()->add(cursor.block()); + } else { + listFmt.setIndent(listFmt.indent() + amount); + cursor.createList(listFmt); + } + } else { + QTextBlockFormat blockFmt = cursor.blockFormat(); + blockFmt.setIndent(blockFmt.indent() + amount); + cursor.setBlockFormat(blockFmt); + } + cursor.endEditBlock(); +} + void TextEdit::currentCharFormatChanged(const QTextCharFormat &format) { fontChanged(format.font()); diff --git a/examples/widgets/richtext/textedit/textedit.h b/examples/widgets/richtext/textedit/textedit.h index c253548a4f..9e50166c6f 100644 --- a/examples/widgets/richtext/textedit/textedit.h +++ b/examples/widgets/richtext/textedit/textedit.h @@ -97,6 +97,8 @@ private slots: void textColor(); void textAlign(QAction *a); void setChecked(bool checked); + void indent(); + void unindent(); void currentCharFormatChanged(const QTextCharFormat &format); void cursorPositionChanged(); @@ -111,6 +113,7 @@ private: void setupTextActions(); bool maybeSave(); void setCurrentFileName(const QString &fileName); + void modifyIndentation(int amount); void mergeFormatOnWordOrSelection(const QTextCharFormat &format); void fontChanged(const QFont &f); @@ -126,6 +129,8 @@ private: QAction *actionAlignCenter; QAction *actionAlignRight; QAction *actionAlignJustify; + QAction *actionIndentLess; + QAction *actionIndentMore; QAction *actionToggleCheckState; QAction *actionUndo; QAction *actionRedo; diff --git a/examples/widgets/richtext/textedit/textedit.qrc b/examples/widgets/richtext/textedit/textedit.qrc index 8016a07ca0..1641acc207 100644 --- a/examples/widgets/richtext/textedit/textedit.qrc +++ b/examples/widgets/richtext/textedit/textedit.qrc @@ -13,6 +13,8 @@ images/mac/fileopen.png images/mac/fileprint.png images/mac/filesave.png + images/mac/format-indent-less.png + images/mac/format-indent-more.png images/mac/textbold.png images/mac/textcenter.png images/mac/textitalic.png @@ -34,6 +36,8 @@ images/win/fileopen.png images/win/fileprint.png images/win/filesave.png + images/win/format-indent-less.png + images/win/format-indent-more.png images/win/textbold.png images/win/textcenter.png images/win/textitalic.png -- cgit v1.2.3 From 1b8a1e04efb4ea71803edf8c122db2837fe23af9 Mon Sep 17 00:00:00 2001 From: Shawn Rutledge Date: Mon, 6 May 2019 17:03:45 +0200 Subject: Fix heading level in style combobox in TextEdit example Amends 0df30ff22e50aa301791fc72f106ab15ce385a6a: when adding the checked and unchecked styles to the combobox, it changed the offsets for the heading styles; so the combobox stopped changing to the correct index when clicking on a heading, and also changed the heading two sizes smaller than it should when attempting to select a different heading level. Change-Id: Ib3f61987c786e34f32a81bf7b3ebc5ca730f40df Reviewed-by: Gatis Paeglis --- examples/widgets/richtext/textedit/textedit.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp index ced77a62ce..996bb8e0a4 100644 --- a/examples/widgets/richtext/textedit/textedit.cpp +++ b/examples/widgets/richtext/textedit/textedit.cpp @@ -691,7 +691,7 @@ void TextEdit::textStyle(int styleIndex) if (style == QTextListFormat::ListStyleUndefined) { blockFmt.setObjectIndex(-1); - int headingLevel = styleIndex >= 9 ? styleIndex - 9 + 1 : 0; // H1 to H6, or Standard + int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; // H1 to H6, or Standard blockFmt.setHeadingLevel(headingLevel); cursor.setBlockFormat(blockFmt); @@ -837,7 +837,7 @@ void TextEdit::cursorPositionChanged() } } else { int headingLevel = textEdit->textCursor().blockFormat().headingLevel(); - comboStyle->setCurrentIndex(headingLevel ? headingLevel + 8 : 0); + comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0); } } -- cgit v1.2.3 From 92f984273262531f909ede17a324f546fe502b5c Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Mon, 6 May 2019 14:00:53 +0200 Subject: Deprecate conversion functions between QList and QSet Users should use range constructors instead to do the conversion. Keep conversion methods between QList and QVector as these will turn into a no-op in Qt 6, whereas forcing people to use range constructors would lead to deep copies of the data. Change-Id: Id9fc9e4d007044e019826da523e8418857c91283 Reviewed-by: Simon Hausmann --- examples/opengl/contextinfo/widget.cpp | 2 +- examples/widgets/painting/pathstroke/pathstroke.cpp | 3 ++- examples/widgets/painting/shared/hoverpoints.cpp | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/opengl/contextinfo/widget.cpp b/examples/opengl/contextinfo/widget.cpp index b1b7076503..0762c91662 100644 --- a/examples/opengl/contextinfo/widget.cpp +++ b/examples/opengl/contextinfo/widget.cpp @@ -384,7 +384,7 @@ void Widget::renderWindowReady() m_output->append(tr("Qt OpenGL library handle: %1") .arg(QString::number(qintptr(QOpenGLContext::openGLModuleHandle()), 16))); - QList extensionList = context->extensions().toList(); + QList extensionList = context->extensions().values(); std::sort(extensionList.begin(), extensionList.end()); m_extensions->append(tr("Found %1 extensions:").arg(extensionList.count())); for (const QByteArray &ext : qAsConst(extensionList)) diff --git a/examples/widgets/painting/pathstroke/pathstroke.cpp b/examples/widgets/painting/pathstroke/pathstroke.cpp index 03e55bb2a2..e4009f0b1a 100644 --- a/examples/widgets/painting/pathstroke/pathstroke.cpp +++ b/examples/widgets/painting/pathstroke/pathstroke.cpp @@ -611,7 +611,8 @@ bool PathStrokeRenderer::event(QEvent *e) case Qt::TouchPointPressed: { // find the point, move it - QSet activePoints = QSet::fromList(m_fingerPointMapping.values()); + const auto mappedPoints = m_fingerPointMapping.values(); + QSet activePoints = QSet(mappedPoints.begin(), mappedPoints.end()); int activePoint = -1; qreal distance = -1; const int pointsCount = m_points.size(); diff --git a/examples/widgets/painting/shared/hoverpoints.cpp b/examples/widgets/painting/shared/hoverpoints.cpp index 74c78088ad..2032fb5a2c 100644 --- a/examples/widgets/painting/shared/hoverpoints.cpp +++ b/examples/widgets/painting/shared/hoverpoints.cpp @@ -180,7 +180,8 @@ bool HoverPoints::eventFilter(QObject *object, QEvent *event) case Qt::TouchPointPressed: { // find the point, move it - QSet activePoints = QSet::fromList(m_fingerPointMapping.values()); + const auto mappedPoints = m_fingerPointMapping.values(); + QSet activePoints = QSet(mappedPoints.begin(), mappedPoints.end()); int activePoint = -1; qreal distance = -1; const int pointsCount = m_points.size(); -- cgit v1.2.3 From ce1830fd21751e90060d77ba529bcd8904555587 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 24 Apr 2019 11:26:58 +0200 Subject: Migrate Windows system libs to external dependencies Started-by: Oswald Buddenhagen Change-Id: I211ce3252b836894aeeac1c85eb316d9596bca57 Reviewed-by: Oliver Wolff --- examples/network/bearermonitor/bearermonitor.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/network/bearermonitor/bearermonitor.pro b/examples/network/bearermonitor/bearermonitor.pro index 7d90b408e0..16ac41298a 100644 --- a/examples/network/bearermonitor/bearermonitor.pro +++ b/examples/network/bearermonitor/bearermonitor.pro @@ -13,7 +13,7 @@ FORMS = bearermonitor_240_320.ui \ bearermonitor_640_480.ui \ sessionwidget.ui -win32:LIBS += -lws2_32 +win32: QMAKE_USE += ws2_32 CONFIG += console -- cgit v1.2.3 From 45aa3c73f78c6c06874d0f826e1f112976cd522d Mon Sep 17 00:00:00 2001 From: Laszlo Agocs Date: Fri, 10 May 2019 13:42:02 +0200 Subject: hellogles3: Request core profile context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ...instead of compatibility, in order to play nice with systems that have no compatibility profile support (macOS). Instancing needs OpenGL 3.x so sticking with 2.x contexts is not an option. The example looks fully compatible with core profile so its functionality should not change. Change-Id: If0d554a6208973aa8a4fb86757e246d170cd0e71 Fixes: QTBUG-75680 Reviewed-by: Tor Arne Vestbø --- examples/opengl/hellogles3/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/opengl/hellogles3/main.cpp b/examples/opengl/hellogles3/main.cpp index 29b3b9617a..9451b2882f 100644 --- a/examples/opengl/hellogles3/main.cpp +++ b/examples/opengl/hellogles3/main.cpp @@ -69,11 +69,11 @@ int main(int argc, char *argv[]) QSurfaceFormat fmt; fmt.setDepthBufferSize(24); - // Request OpenGL 3.3 compatibility or OpenGL ES 3.0. + // Request OpenGL 3.3 core or OpenGL ES 3.0. if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) { - qDebug("Requesting 3.3 compatibility context"); + qDebug("Requesting 3.3 core context"); fmt.setVersion(3, 3); - fmt.setProfile(QSurfaceFormat::CompatibilityProfile); + fmt.setProfile(QSurfaceFormat::CoreProfile); } else { qDebug("Requesting 3.0 context"); fmt.setVersion(3, 0); -- cgit v1.2.3 From 4f6eb43898aa14fef5f3a54966b340188271d85e Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 12 May 2019 21:30:10 +0200 Subject: QtCore: mark obsolete enumerations as deprecated The following enumerations were obsolete for a log time but not marked as deprecated: - WA_NoBackground - WA_MacNoClickThrough - WA_MacBrushedMetal - WA_MacMetalStyle - WA_MSWindowsUseDirect3D - WA_MacFrameworkScaled - AA_MSWindowsUseDirect3DByDefault - AA_X11InitThreads - ImMicroFocus mark them as deprecated and remove the usage inside QtBase so they can be removed with Qt6 Change-Id: Ia087a7e1d0ff1945286895be6425a6cceaa483fb Reviewed-by: Friedemann Kleint Reviewed-by: Richard Moe Gustavsen --- examples/widgets/painting/gradients/gradients.cpp | 2 +- examples/widgets/tools/plugandpaint/app/paintarea.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/widgets/painting/gradients/gradients.cpp b/examples/widgets/painting/gradients/gradients.cpp index 8df45be8d9..a4528ce06f 100644 --- a/examples/widgets/painting/gradients/gradients.cpp +++ b/examples/widgets/painting/gradients/gradients.cpp @@ -72,7 +72,7 @@ ShadeWidget::ShadeWidget(ShadeType type, QWidget *parent) setPalette(pal); } else { - setAttribute(Qt::WA_NoBackground); + setAttribute(Qt::WA_OpaquePaintEvent); } QPolygonF points; diff --git a/examples/widgets/tools/plugandpaint/app/paintarea.cpp b/examples/widgets/tools/plugandpaint/app/paintarea.cpp index 4295e04cc0..e225d78398 100644 --- a/examples/widgets/tools/plugandpaint/app/paintarea.cpp +++ b/examples/widgets/tools/plugandpaint/app/paintarea.cpp @@ -59,7 +59,7 @@ PaintArea::PaintArea(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); - setAttribute(Qt::WA_NoBackground); + setAttribute(Qt::WA_OpaquePaintEvent); theImage.fill(qRgb(255, 255, 255)); } -- cgit v1.2.3 From edb53d761e62ab2e2d4832399a27d580af5a24c4 Mon Sep 17 00:00:00 2001 From: Christian Ehrlicher Date: Sun, 12 May 2019 21:23:26 +0200 Subject: QFileDialog: mark obsolete enum DontUseSheet as deprecated QFileDialog::DontUseSheet is obsolete since 4.5 and not used anywhere inside the Qt code base. Mark it as deprecated and remove the last usage in the examples. Change-Id: If3d23fd5906314e6ebc7080efa79da14a2aa2720 Reviewed-by: Friedemann Kleint Reviewed-by: Richard Moe Gustavsen --- examples/widgets/dialogs/standarddialogs/dialog.cpp | 1 - 1 file changed, 1 deletion(-) (limited to 'examples') diff --git a/examples/widgets/dialogs/standarddialogs/dialog.cpp b/examples/widgets/dialogs/standarddialogs/dialog.cpp index 1830b21e8f..c91a594490 100644 --- a/examples/widgets/dialogs/standarddialogs/dialog.cpp +++ b/examples/widgets/dialogs/standarddialogs/dialog.cpp @@ -287,7 +287,6 @@ Dialog::Dialog(QWidget *parent) fileDialogOptionsWidget->addCheckBox(tr("Show directories only"), QFileDialog::ShowDirsOnly); fileDialogOptionsWidget->addCheckBox(tr("Do not resolve symlinks"), QFileDialog::DontResolveSymlinks); fileDialogOptionsWidget->addCheckBox(tr("Do not confirm overwrite"), QFileDialog::DontConfirmOverwrite); - 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); -- cgit v1.2.3 From b4a88aa7589d9d09fd54a5a7df29036a74293116 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 14 Dec 2017 00:29:30 +0100 Subject: examples: port away from Java-style iterators There's no reason to use them here, the Mutable is misleading in a few instances, ranged-for is much simpler, and more future-proof. Change-Id: Ifd5eaae95bbaa0b4cf0f435e6cfee6d778817b44 Reviewed-by: David Faure --- examples/opengl/legacy/overpainting/glwidget.cpp | 6 +----- examples/opengl/qopenglwidget/glwidget.cpp | 7 ++----- examples/qtconcurrent/wordcount/main.cpp | 5 +---- examples/widgets/tools/i18n/languagechooser.cpp | 7 ++----- 4 files changed, 6 insertions(+), 19 deletions(-) (limited to 'examples') diff --git a/examples/opengl/legacy/overpainting/glwidget.cpp b/examples/opengl/legacy/overpainting/glwidget.cpp index f98d043c5c..0094f8ead7 100644 --- a/examples/opengl/legacy/overpainting/glwidget.cpp +++ b/examples/opengl/legacy/overpainting/glwidget.cpp @@ -247,12 +247,8 @@ void GLWidget::createBubbles(int number) //! [13] void GLWidget::animate() { - QMutableListIterator iter(bubbles); - - while (iter.hasNext()) { - Bubble *bubble = iter.next(); + for (Bubble *bubble : qAsConst(bubbles)) bubble->move(rect()); - } update(); } //! [13] diff --git a/examples/opengl/qopenglwidget/glwidget.cpp b/examples/opengl/qopenglwidget/glwidget.cpp index 946b2bec67..5057291f12 100644 --- a/examples/opengl/qopenglwidget/glwidget.cpp +++ b/examples/opengl/qopenglwidget/glwidget.cpp @@ -399,12 +399,9 @@ void GLWidget::paintGL() painter.end(); - QMutableListIterator iter(m_bubbles); - - while (iter.hasNext()) { - Bubble *bubble = iter.next(); + for (Bubble *bubble : qAsConst(m_bubbles)) bubble->move(rect()); - } + if (!(m_frames % 100)) { m_time.start(); m_frames = 0; diff --git a/examples/qtconcurrent/wordcount/main.cpp b/examples/qtconcurrent/wordcount/main.cpp index ff7ea24ee7..32cb4d0e08 100644 --- a/examples/qtconcurrent/wordcount/main.cpp +++ b/examples/qtconcurrent/wordcount/main.cpp @@ -126,11 +126,8 @@ WordCount countWords(const QString &file) // at a time. void reduce(WordCount &result, const WordCount &w) { - QMapIterator i(w); - while (i.hasNext()) { - i.next(); + for (auto i = w.begin(), end = w.end(); i != end; ++i) result[i.key()] += i.value(); - } } int main(int argc, char** argv) diff --git a/examples/widgets/tools/i18n/languagechooser.cpp b/examples/widgets/tools/i18n/languagechooser.cpp index f07d0ddee3..963165ff81 100644 --- a/examples/widgets/tools/i18n/languagechooser.cpp +++ b/examples/widgets/tools/i18n/languagechooser.cpp @@ -163,11 +163,8 @@ QStringList LanguageChooser::findQmFiles() QDir dir(":/translations"); QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name); - QMutableStringListIterator i(fileNames); - while (i.hasNext()) { - i.next(); - i.setValue(dir.filePath(i.value())); - } + for (QString &fileName : fileNames) + fileName = dir.filePath(fileName); return fileNames; } -- cgit v1.2.3 From ce211b1f837ce3212074800e92dee30d95546d94 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Fri, 17 May 2019 15:37:45 +0200 Subject: Fix qdoc warnings for Qt 5.14 src/corelib/tools/qstring.cpp:9505:clang found diagnostics parsing \fn int QLatin1String::indexOf(QLatin1String l1, int from Qt::CaseSensitivity cs) const error: expected ')' error: out-of-line definition of 'indexOf' does not match any declaration in 'QLatin1String' src/corelib/tools/qstringview.cpp:723:clang found diagnostics parsing \fn qsizetype QStringView::indexOf(QLatin1String l1, qsizetype from Qt::CaseSensitivity cs) const error: expected ')' error: out-of-line definition of 'indexOf' does not match any declaration in 'QStringView' src/corelib/tools/qstringview.cpp:822:Unknown command '\t' src/corelib/tools/qstringview.cpp:825:Unknown command '\t' src/corelib/tools/qstringview.cpp:826:Unknown command '\t' src/corelib/tools/qstringview.cpp:831:Unknown command '\t' src/corelib/global/qnamespace.qdoc:2448:Undocumented enum item 'MarkdownText' in Qt::TextFormat src/corelib/tools/qstringmatcher.cpp:183:No such parameter 'pattern' in QStringMatcher::QStringMatcher() src/network/ssl/qsslerror.cpp:58:Undocumented enum item 'CertificateStatusUnknown' in QSslError::SslError src/gui/kernel/qevent.cpp:5321:Undocumented parameter 'screenOrientation' in QScreenOrientationChangeEvent::QScreenOrientationChangeEvent() src/gui/kernel/qevent.cpp:5321:Undocumented parameter 'screen' in QScreenOrientationChangeEvent::QScreenOrientationChangeEvent() src/gui/kernel/qevent.cpp:5321:No such parameter 'orientation' in QScreenOrientationChangeEvent::QScreenOrientationChangeEvent() src/gui/text/qtextformat.cpp:532:Undocumented enum item 'BlockCodeLanguage' in QTextFormat::Property src/gui/text/qtextformat.cpp:532:Undocumented enum item 'BlockQuoteLevel' in QTextFormat::Property src/gui/text/qtextformat.cpp:532:Undocumented enum item 'BlockMarker' in QTextFormat::Property src/gui/text/qtextdocument.cpp:3294:Undocumented parameter 'features' in QTextDocument::toMarkdown() src/gui/painting/qcolorspace.cpp:659:Undocumented parameter 'colorSpace1' in QColorSpace::operator!=() src/gui/painting/qcolorspace.cpp:659:Undocumented parameter 'colorSpace2' in QColorSpace::operator!=() src/gui/painting/qcolorspace.cpp:659:No such parameter 'colorspace1' in QColorSpace::operator!=() src/gui/painting/qcolorspace.cpp:659:No such parameter 'colorspace2' in QColorSpace::operator!=() examples/widgets/doc/src/icons.qdoc:269:Command '\snippet (//! [43])' failed at end of file 'widgets/icons/iconpreviewarea.cpp' src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_DialogRetryButton' in QStyle::StandardPixmap src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_DialogYesToAllButton' in QStyle::StandardPixmap src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_DialogIgnoreButton' in QStyle::StandardPixmap src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_DialogNoToAllButton' in QStyle::StandardPixmap src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_DialogAbortButton' in QStyle::StandardPixmap src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_RestoreDefaultsButton' in QStyle::StandardPixmap src/widgets/styles/qstyle.cpp:2026:Undocumented enum item 'SP_DialogSaveAllButton' in QStyle::StandardPixmap src/testlib/qtestcase.qdoc:439:Undocumented parameter 'TestClass' in QTest::QTEST_HIGHDPI_SCALING_MAIN src/testlib/qtestcase.qdoc:452:Undocumented parameter 'TestClass' in QTest::QTEST_NO_HIGHDPI_SCALING_MAIN Change-Id: Ib0e9bf81c5caaa6b1fc644ac92085af47c600e0e Reviewed-by: Shawn Rutledge Reviewed-by: Anton Kudryavtsev Reviewed-by: Paul Wicking --- examples/widgets/doc/src/icons.qdoc | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) (limited to 'examples') diff --git a/examples/widgets/doc/src/icons.qdoc b/examples/widgets/doc/src/icons.qdoc index 60cb9062c2..7aae0491d6 100644 --- a/examples/widgets/doc/src/icons.qdoc +++ b/examples/widgets/doc/src/icons.qdoc @@ -262,12 +262,7 @@ 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. + using C++ 11 initializer lists. We need two public functions to set the current icon and the icon's size. In addition the class has three private functions: We -- cgit v1.2.3 From b4a1336bb0482298602f47a77f6a44aac513a92a Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Thu, 23 May 2019 15:40:37 +0200 Subject: Fix memory leak with arthur style ASAN reports a leak here, so let's delete the style after the widgets using them have been destroyed. Change-Id: I0e8603fc5d2d0c13deca35a1c0020646c65eaf49 Reviewed-by: Allan Sandfeld Jensen --- examples/widgets/painting/composition/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/widgets/painting/composition/main.cpp b/examples/widgets/painting/composition/main.cpp index 2eaeaba2c5..1ffa29dddc 100644 --- a/examples/widgets/painting/composition/main.cpp +++ b/examples/widgets/painting/composition/main.cpp @@ -56,13 +56,13 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); + QScopedPointer arthurStyle(new ArthurStyle()); CompositionWidget compWidget(nullptr); - QStyle *arthurStyle = new ArthurStyle(); - compWidget.setStyle(arthurStyle); + compWidget.setStyle(arthurStyle.data()); const QList widgets = compWidget.findChildren(); for (QWidget *w : widgets) - w->setStyle(arthurStyle); + w->setStyle(arthurStyle.data()); compWidget.show(); return app.exec(); -- cgit v1.2.3 From c9b7cc349a13b722ecd636ec4eb8e21f9f712add Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Thu, 23 May 2019 13:51:05 +0200 Subject: Remove usages of Q_OS_WINCE This platform is history. Change-Id: Iddfab008a509f4828c321730414c8204055cf7af Reviewed-by: Maurice Kalinowski --- examples/embedded/raycasting/raycasting.cpp | 4 ---- 1 file changed, 4 deletions(-) (limited to 'examples') diff --git a/examples/embedded/raycasting/raycasting.cpp b/examples/embedded/raycasting/raycasting.cpp index d37b9f5d2e..7213811213 100644 --- a/examples/embedded/raycasting/raycasting.cpp +++ b/examples/embedded/raycasting/raycasting.cpp @@ -255,11 +255,7 @@ public: protected: void resizeEvent(QResizeEvent*) { -#if defined(Q_OS_WINCE_WM) - touchDevice = true; -#else touchDevice = false; -#endif if (touchDevice) { if (width() < height()) { trackPad = QRect(0, height() / 2, width(), height() / 2); -- cgit v1.2.3 From 77e708d1676803ce4ed7a2511fd80f8848522c63 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 23 May 2019 10:39:56 +0200 Subject: Torrent example: replace Java-style iteration with STL iterators MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Java-iterators are going to be deprecated. Change-Id: I2e6353f3fd9e2ddaf0767e7f6cea713249d9591e Reviewed-by: Mårten Nordheim Reviewed-by: Paul Wicking --- examples/network/torrent/ratecontroller.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'examples') diff --git a/examples/network/torrent/ratecontroller.cpp b/examples/network/torrent/ratecontroller.cpp index 47b49dba30..87c65096b6 100644 --- a/examples/network/torrent/ratecontroller.cpp +++ b/examples/network/torrent/ratecontroller.cpp @@ -123,11 +123,11 @@ void RateController::transfer() qint64 writeChunk = qMax(1, bytesToWrite / pendingSockets.size()); qint64 readChunk = qMax(1, bytesToRead / pendingSockets.size()); - QSetIterator it(pendingSockets); - while (it.hasNext() && (bytesToWrite > 0 || bytesToRead > 0)) { - PeerWireClient *socket = it.next(); + for (auto it = pendingSockets.begin(), end = pendingSockets.end(); it != end && (bytesToWrite > 0 || bytesToRead > 0); /*erasing*/) { + auto current = it++; + PeerWireClient *socket = *current; if (socket->state() != QAbstractSocket::ConnectedState) { - pendingSockets.remove(socket); + pendingSockets.erase(current); continue; } @@ -156,7 +156,7 @@ void RateController::transfer() if (dataTransferred && socket->canTransferMore()) canTransferMore = true; else - pendingSockets.remove(socket); + pendingSockets.erase(current); } } while (canTransferMore && (bytesToWrite > 0 || bytesToRead > 0) && !pendingSockets.isEmpty()); -- cgit v1.2.3 From 54590c4f8acc8e1be24a1d4d4bb0d716018c9ba0 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Wed, 22 May 2019 22:01:20 +0200 Subject: Torrent example: rewrite some very convoluted code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The old code iterated over the peer list, inserting active peers into a QSet, curiously not stopping to search for clients if it had already determined the peer to be active. It then iterated over the peers again, storing the indexes of the peers it had determined to be active in the first loop, in a QList. It _then_ iterated over the index list, in reverse, calling removeAt() on the peers list. That's a remove_if! The twist is, that only some maximum number of inactive peers should be removed, just enough to bring the number of peers below a predefined number. To solve, use a lambda that keeps track of the number of times it has returned true, returning false once the count drops to zero. We can't use a mutable lambda here, since the STL algorithms are allowed to copy the predicate as many times as they wish, and, indeed, remove_if is commonly implemented by calling find_if. But the standard guarantees exactly one application of the predicate per element, so we can assume that we're not called again on the same element, and therefore keep a reference to an external count. With this, what was a horrible mess becomes a single call to remove_if. Also change a while(--n) c.removeFirst() loop to a single call of range-erase. Change-Id: I6c6a54a1805e5b376800e1116e7aec643e95e4e1 Reviewed-by: Mårten Nordheim --- examples/network/torrent/torrentclient.cpp | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) (limited to 'examples') diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp index d01a5f3d9e..b5ebad54f4 100644 --- a/examples/network/torrent/torrentclient.cpp +++ b/examples/network/torrent/torrentclient.cpp @@ -1484,30 +1484,26 @@ void TorrentClient::addToPeerList(const QList &peerList) // of the peers that have no (or low) activity. int maxPeers = ConnectionManager::instance()->maxConnections() * 3; if (d->peers.size() > maxPeers) { + auto tooMany = d->peers.size() - maxPeers; + // Find what peers are currently connected & active - QSet activePeers; - for (TorrentPeer *peer : qAsConst(d->peers)) { + const auto firstNInactivePeers = [&tooMany, this] (TorrentPeer *peer) { + if (!tooMany) + return false; for (const PeerWireClient *client : qAsConst(d->connections)) { if (client->peer() == peer && (client->downloadSpeed() + client->uploadSpeed()) > 1024) - activePeers << peer; + return false; } - } - + --tooMany; + return true; + }; // Remove inactive peers from the peer list until we're below // the max connections count. - QList toRemove; - for (int i = 0; i < d->peers.size() && (d->peers.size() - toRemove.size()) > maxPeers; ++i) { - if (!activePeers.contains(d->peers.at(i))) - toRemove << i; - } - QListIterator toRemoveIterator(toRemove); - toRemoveIterator.toBack(); - while (toRemoveIterator.hasPrevious()) - d->peers.removeAt(toRemoveIterator.previous()); - + d->peers.erase(std::remove_if(d->peers.begin(), d->peers.end(), + firstNInactivePeers), + d->peers.end()); // If we still have too many peers, remove the oldest ones. - while (d->peers.size() > maxPeers) - d->peers.takeFirst(); + d->peers.erase(d->peers.begin(), d->peers.begin() + tooMany); } if (d->state != Paused && d->state != Stopping && d->state != Idle) { -- cgit v1.2.3 From f0463f0cc6e2091bc1797d0fc18cb538f7ec2cd0 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 23 May 2019 10:47:35 +0200 Subject: Torrent example: add missing qAsConst() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The function is const, but the d-pointer doesn't propagate it (raw pointer), so we need the qAsConst() even here. Change-Id: I9d2e1f7715abb3dc67a87cdadaa7ded971b15848 Reviewed-by: Mårten Nordheim --- examples/network/torrent/torrentclient.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp index b5ebad54f4..bd050153a4 100644 --- a/examples/network/torrent/torrentclient.cpp +++ b/examples/network/torrent/torrentclient.cpp @@ -720,9 +720,9 @@ QList TorrentClient::weighedFreePeers() const qint64 now = QDateTime::currentSecsSinceEpoch(); QList freePeers; QMap connectionsPerPeer; - for (TorrentPeer *peer : d->peers) { + for (TorrentPeer *peer : qAsConst(d->peers)) { bool busy = false; - for (PeerWireClient *client : d->connections) { + for (PeerWireClient *client : qAsConst(d->connections)) { if (client->state() == PeerWireClient::ConnectedState && client->peerAddress() == peer->address && client->peerPort() == peer->port) { -- cgit v1.2.3 From eae4668afaaed2723383d8c19858d3e212f3e8ec Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 23 May 2019 12:40:12 +0200 Subject: Torrent example: replace a QMultiMap with a sorted vector This came about trying to remove the Java-style iterator. It was used to iterate in reverse order, something QMap can't do, easily, due to lack of rbegin()/rend(). Instead of writing ugly loops, use a vector of pairs, fill it, sort it, then iterate over that one in reverse. Change-Id: I09c8a2732a0699fff4c497778745523e20d348a1 Reviewed-by: Paul Wicking --- examples/network/torrent/torrentclient.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'examples') diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp index bd050153a4..b4cbbb7a45 100644 --- a/examples/network/torrent/torrentclient.cpp +++ b/examples/network/torrent/torrentclient.cpp @@ -1084,25 +1084,25 @@ void TorrentClient::scheduleUploads() // seeding, we sort by upload speed. Seeds are left out; there's // no use in unchoking them. QList allClients = d->connections; - QMultiMap transferSpeeds; + QVector> transferSpeeds; for (PeerWireClient *client : qAsConst(allClients)) { if (client->state() == QAbstractSocket::ConnectedState && client->availablePieces().count(true) != d->pieceCount) { if (d->state == Seeding) { - transferSpeeds.insert(client->uploadSpeed(), client); + transferSpeeds.push_back({client->uploadSpeed(), client}); } else { - transferSpeeds.insert(client->downloadSpeed(), client); + transferSpeeds.push_back({client->downloadSpeed(), client}); } } } + std::sort(transferSpeeds.begin(), transferSpeeds.end()); + // Unchoke the top 'MaxUploads' downloaders (peers that we are // uploading to) and choke all others. int maxUploaders = MaxUploads; - QMapIterator it(transferSpeeds); - it.toBack(); - while (it.hasPrevious()) { - PeerWireClient *client = it.previous().value(); + for (auto rit = transferSpeeds.crbegin(), rend = transferSpeeds.crend(); rit != rend; ++rit) { + PeerWireClient *client = rit->second; bool interested = (client->peerWireState() & PeerWireClient::PeerIsInterested); if (maxUploaders) { -- cgit v1.2.3