qt 6.5.1 original

This commit is contained in:
kleuter
2023-10-29 23:33:08 +01:00
parent 71d22ab6b0
commit 85d238dfda
21202 changed files with 5499099 additions and 0 deletions

View File

@ -0,0 +1,33 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
if(NOT TARGET Qt6::Widgets)
return()
endif()
if(QT_FEATURE_animation)
add_subdirectory(animation)
endif()
add_subdirectory(desktop)
add_subdirectory(dialogs)
add_subdirectory(effects)
qt_internal_add_example(gallery)
add_subdirectory(gestures)
add_subdirectory(graphicsview)
add_subdirectory(itemviews)
add_subdirectory(layouts)
add_subdirectory(painting)
add_subdirectory(richtext)
add_subdirectory(scroller)
add_subdirectory(tools)
add_subdirectory(touch)
add_subdirectory(tutorials)
add_subdirectory(widgets)
if(QT_FEATURE_draganddrop)
add_subdirectory(draganddrop)
endif()
if(QT_FEATURE_cursor)
add_subdirectory(mainwindows)
endif()
if(QT_FEATURE_opengl AND TARGET Qt6::Gui)
qt_internal_add_example(windowcontainer)
endif()

View File

@ -0,0 +1 @@
qt_internal_add_example(easing)

View File

@ -0,0 +1,8 @@
The animation framework aims to provide an easy way for creating animated and
smooth GUI's. By animating Qt properties, the framework provides great freedom
for animating widgets and other QObjects. The framework can also be used with
the Graphics View framework.
Documentation for these examples can be found via the Examples
link in the main Qt documentation.

View File

@ -0,0 +1,3 @@
TEMPLATE = \
subdirs
SUBDIRS += easing

View File

@ -0,0 +1,51 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(easing LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/animation/easing")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(easing
animation.h
form.ui
main.cpp
window.cpp window.h
)
set_target_properties(easing PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(easing PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
# Resources:
set(easing_resource_files
"images/qt-logo.png"
)
qt_add_resources(easing "easing"
PREFIX
"/"
FILES
${easing_resource_files}
)
install(TARGETS easing
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,63 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ANIMATION_H
#define ANIMATION_H
#include <QtWidgets>
#include <QtCore/qpropertyanimation.h>
class Animation : public QPropertyAnimation {
public:
enum PathType {
LinearPath,
CirclePath,
NPathTypes
};
Animation(QObject *target, const QByteArray &prop, QObject *parent = nullptr)
: QPropertyAnimation(target, prop, parent)
{
setPathType(LinearPath);
}
void setPathType(PathType pathType)
{
if (pathType >= NPathTypes)
qWarning("Unknown pathType %d", pathType);
m_pathType = pathType;
m_path = QPainterPath();
}
void updateCurrentTime(int currentTime) override
{
if (m_pathType == CirclePath) {
if (m_path.isEmpty()) {
QPointF to = endValue().toPointF();
QPointF from = startValue().toPointF();
m_path.moveTo(from);
m_path.addEllipse(QRectF(from, to));
}
int dura = duration();
const qreal progress = ((dura == 0) ? 1 : ((((currentTime - 1) % dura) + 1) / qreal(dura)));
qreal easedProgress = easingCurve().valueForProgress(progress);
if (easedProgress > 1.0) {
easedProgress -= 1.0;
} else if (easedProgress < 0) {
easedProgress += 1.0;
}
QPointF pt = m_path.pointAtPercent(easedProgress);
updateCurrentValue(pt);
emit valueChanged(pt);
} else {
QPropertyAnimation::updateCurrentTime(currentTime);
}
}
QPainterPath m_path;
PathType m_pathType;
};
#endif // ANIMATION_H

View File

@ -0,0 +1,15 @@
QT += widgets
requires(qtConfig(listwidget))
HEADERS = window.h \
animation.h
SOURCES = main.cpp \
window.cpp
FORMS = form.ui
RESOURCES = easing.qrc
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/animation/easing
INSTALLS += target

View File

@ -0,0 +1,5 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/qt-logo.png</file>
</qresource>
</RCC>

View File

@ -0,0 +1,270 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>545</width>
<height>471</height>
</rect>
</property>
<property name="windowTitle">
<string>Easing curves</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<widget class="QListWidget" name="easingCurvePicker">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>120</height>
</size>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="movement">
<enum>QListView::Static</enum>
</property>
<property name="isWrapping" stdset="0">
<bool>false</bool>
</property>
<property name="viewMode">
<enum>QListView::IconMode</enum>
</property>
<property name="selectionRectVisible">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="title">
<string>Path type</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QRadioButton" name="lineRadio">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>40</height>
</size>
</property>
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="text">
<string>Line</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string>buttonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="0">
<widget class="QRadioButton" name="circleRadio">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>40</height>
</size>
</property>
<property name="text">
<string>Circle</string>
</property>
<attribute name="buttonGroup">
<string>buttonGroup</string>
</attribute>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Properties</string>
</property>
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>Period</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QDoubleSpinBox" name="periodSpinBox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="minimum">
<double>-1.000000000000000</double>
</property>
<property name="singleStep">
<double>0.100000000000000</double>
</property>
<property name="value">
<double>-1.000000000000000</double>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QDoubleSpinBox" name="amplitudeSpinBox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="minimum">
<double>-1.000000000000000</double>
</property>
<property name="singleStep">
<double>0.100000000000000</double>
</property>
<property name="value">
<double>-1.000000000000000</double>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_3">
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>Overshoot</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QDoubleSpinBox" name="overshootSpinBox">
<property name="enabled">
<bool>false</bool>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="minimum">
<double>-1.000000000000000</double>
</property>
<property name="singleStep">
<double>0.100000000000000</double>
</property>
<property name="value">
<double>-1.000000000000000</double>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_2">
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>Amplitude</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="1" column="1">
<widget class="QGraphicsView" name="graphicsView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
<buttongroups>
<buttongroup name="buttonGroup"/>
</buttongroups>
</ui>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -0,0 +1,17 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "window.h"
int main(int argc, char **argv)
{
Q_INIT_RESOURCE(easing);
QApplication app(argc, argv);
Window w;
w.resize(400, 400);
w.show();
return app.exec();
}

View File

@ -0,0 +1,162 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "window.h"
Window::Window(QWidget *parent)
: QWidget(parent),
m_iconSize(64, 64)
{
m_ui.setupUi(this);
m_ui.easingCurvePicker->setIconSize(m_iconSize);
m_ui.easingCurvePicker->setMinimumHeight(m_iconSize.height() + 50);
m_ui.buttonGroup->setId(m_ui.lineRadio, 0);
m_ui.buttonGroup->setId(m_ui.circleRadio, 1);
QEasingCurve dummy;
m_ui.periodSpinBox->setValue(dummy.period());
m_ui.amplitudeSpinBox->setValue(dummy.amplitude());
m_ui.overshootSpinBox->setValue(dummy.overshoot());
connect(m_ui.easingCurvePicker, &QListWidget::currentRowChanged,
this, &Window::curveChanged);
connect(m_ui.buttonGroup, &QButtonGroup::buttonClicked,
this, &Window::pathChanged);
connect(m_ui.periodSpinBox, &QDoubleSpinBox::valueChanged,
this, &Window::periodChanged);
connect(m_ui.amplitudeSpinBox, &QDoubleSpinBox::valueChanged,
this, &Window::amplitudeChanged);
connect(m_ui.overshootSpinBox, &QDoubleSpinBox::valueChanged,
this, &Window::overshootChanged);
createCurveIcons();
QPixmap pix(QLatin1String(":/images/qt-logo.png"));
m_item = new PixmapItem(pix);
m_scene.addItem(m_item);
m_ui.graphicsView->setScene(&m_scene);
m_anim = new Animation(m_item, "pos", this);
m_anim->setEasingCurve(QEasingCurve::OutBounce);
m_ui.easingCurvePicker->setCurrentRow(int(QEasingCurve::OutBounce));
startAnimation();
}
static QEasingCurve createEasingCurve(QEasingCurve::Type curveType)
{
QEasingCurve curve(curveType);
if (curveType == QEasingCurve::BezierSpline) {
curve.addCubicBezierSegment(QPointF(0.4, 0.1), QPointF(0.6, 0.9), QPointF(1.0, 1.0));
} else if (curveType == QEasingCurve::TCBSpline) {
curve.addTCBSegment(QPointF(0.0, 0.0), 0, 0, 0);
curve.addTCBSegment(QPointF(0.3, 0.4), 0.2, 1, -0.2);
curve.addTCBSegment(QPointF(0.7, 0.6), -0.2, 1, 0.2);
curve.addTCBSegment(QPointF(1.0, 1.0), 0, 0, 0);
}
return curve;
}
void Window::createCurveIcons()
{
QPixmap pix(m_iconSize);
QPainter painter(&pix);
QLinearGradient gradient(0,0, 0, m_iconSize.height());
gradient.setColorAt(0.0, QColor(240, 240, 240));
gradient.setColorAt(1.0, QColor(224, 224, 224));
QBrush brush(gradient);
const QMetaObject &mo = QEasingCurve::staticMetaObject;
QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type"));
// Skip QEasingCurve::Custom
for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) {
painter.fillRect(QRect(QPoint(0, 0), m_iconSize), brush);
QEasingCurve curve = createEasingCurve(static_cast<QEasingCurve::Type>(i));
painter.setPen(QColor(0, 0, 255, 64));
qreal xAxis = m_iconSize.height()/1.5;
qreal yAxis = m_iconSize.width()/3;
painter.drawLine(QLineF(0, xAxis, m_iconSize.width(), xAxis));
painter.drawLine(QLineF(yAxis, 0, yAxis, m_iconSize.height()));
qreal curveScale = m_iconSize.height()/2;
painter.setPen(Qt::NoPen);
// start point
painter.setBrush(Qt::red);
QPoint start(qRound(yAxis), qRound(xAxis - curveScale * curve.valueForProgress(0)));
painter.drawRect(start.x() - 1, start.y() - 1, 3, 3);
// end point
painter.setBrush(Qt::blue);
QPoint end(qRound(yAxis + curveScale), qRound(xAxis - curveScale * curve.valueForProgress(1)));
painter.drawRect(end.x() - 1, end.y() - 1, 3, 3);
QPainterPath curvePath;
curvePath.moveTo(start);
for (qreal t = 0; t <= 1.0; t+=1.0/curveScale) {
QPointF to;
to.setX(yAxis + curveScale * t);
to.setY(xAxis - curveScale * curve.valueForProgress(t));
curvePath.lineTo(to);
}
painter.setRenderHint(QPainter::Antialiasing, true);
painter.strokePath(curvePath, QColor(32, 32, 32));
painter.setRenderHint(QPainter::Antialiasing, false);
QListWidgetItem *item = new QListWidgetItem;
item->setIcon(QIcon(pix));
item->setText(metaEnum.key(i));
m_ui.easingCurvePicker->addItem(item);
}
}
void Window::startAnimation()
{
m_anim->setStartValue(QPointF(0, 0));
m_anim->setEndValue(QPointF(100, 100));
m_anim->setDuration(2000);
m_anim->setLoopCount(-1); // forever
m_anim->start();
}
void Window::curveChanged(int row)
{
QEasingCurve::Type curveType = static_cast<QEasingCurve::Type>(row);
m_anim->setEasingCurve(createEasingCurve(curveType));
m_anim->setCurrentTime(0);
bool isElastic = curveType >= QEasingCurve::InElastic && curveType <= QEasingCurve::OutInElastic;
bool isBounce = curveType >= QEasingCurve::InBounce && curveType <= QEasingCurve::OutInBounce;
m_ui.periodSpinBox->setEnabled(isElastic);
m_ui.amplitudeSpinBox->setEnabled(isElastic || isBounce);
m_ui.overshootSpinBox->setEnabled(curveType >= QEasingCurve::InBack && curveType <= QEasingCurve::OutInBack);
}
void Window::pathChanged(QAbstractButton *button)
{
const int index = m_ui.buttonGroup->id(button);
m_anim->setPathType(Animation::PathType(index));
}
void Window::periodChanged(double value)
{
QEasingCurve curve = m_anim->easingCurve();
curve.setPeriod(value);
m_anim->setEasingCurve(curve);
}
void Window::amplitudeChanged(double value)
{
QEasingCurve curve = m_anim->easingCurve();
curve.setAmplitude(value);
m_anim->setEasingCurve(curve);
}
void Window::overshootChanged(double value)
{
QEasingCurve curve = m_anim->easingCurve();
curve.setOvershoot(value);
m_anim->setEasingCurve(curve);
}

View File

@ -0,0 +1,44 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
#include <QtWidgets>
#include "ui_form.h"
#include "animation.h"
class PixmapItem : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
public:
PixmapItem(const QPixmap &pix) : QGraphicsPixmapItem(pix)
{
}
};
class Window : public QWidget {
Q_OBJECT
public:
Window(QWidget *parent = nullptr);
private slots:
void curveChanged(int row);
void pathChanged(QAbstractButton *button);
void periodChanged(double);
void amplitudeChanged(double);
void overshootChanged(double);
private:
void createCurveIcons();
void startAnimation();
Ui::Form m_ui;
QGraphicsScene m_scene;
PixmapItem *m_item;
Animation *m_anim;
QSize m_iconSize;
};
#endif // WINDOW_H

View File

@ -0,0 +1,2 @@
qt_internal_add_example(screenshot)
qt_internal_add_example(systray)

View File

@ -0,0 +1,10 @@
Qt provides features to enable applications to integrate with the user's
preferred desktop environment.
Features such as system tray icons, access to the desktop widget, and
support for desktop services can be used to improve the appearance of
applications and take advantage of underlying desktop facilities.
Documentation for these examples can be found via the Examples
link in the main Qt documentation.

View File

@ -0,0 +1,2 @@
TEMPLATE = subdirs
SUBDIRS = screenshot systray

View File

@ -0,0 +1,37 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(screenshot LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/desktop/screenshot")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(screenshot
main.cpp
screenshot.cpp screenshot.h
)
set_target_properties(screenshot PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(screenshot PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS screenshot
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,18 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QScreen>
#include "screenshot.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Screenshot screenshot;
screenshot.move(screenshot.screen()->availableGeometry().topLeft() + QPoint(20, 20));
screenshot.show();
return app.exec();
}

View File

@ -0,0 +1,152 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "screenshot.h"
//! [0]
Screenshot::Screenshot()
: screenshotLabel(new QLabel(this))
{
screenshotLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
screenshotLabel->setAlignment(Qt::AlignCenter);
const QRect screenGeometry = screen()->geometry();
screenshotLabel->setMinimumSize(screenGeometry.width() / 8, screenGeometry.height() / 8);
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);
connect(delaySpinBox, &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);
shootScreen();
delaySpinBox->setValue(5);
setWindowTitle(tr("Screenshot"));
resize(300, 200);
}
//! [0]
//! [1]
void Screenshot::resizeEvent(QResizeEvent * /* event */)
{
QSize scaledSize = originalPixmap.size();
scaledSize.scale(screenshotLabel->size(), Qt::KeepAspectRatio);
if (scaledSize != screenshotLabel->pixmap().size())
updateScreenshotLabel();
}
//! [1]
//! [2]
void Screenshot::newScreenshot()
{
if (hideThisWindowCheckBox->isChecked())
hide();
newScreenshotButton->setDisabled(true);
QTimer::singleShot(delaySpinBox->value() * 1000, this, &Screenshot::shootScreen);
}
//! [2]
//! [3]
void Screenshot::saveScreenshot()
{
const QString format = "png";
QString initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
if (initialPath.isEmpty())
initialPath = QDir::currentPath();
initialPath += tr("/untitled.") + format;
QFileDialog fileDialog(this, tr("Save As"), initialPath);
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setFileMode(QFileDialog::AnyFile);
fileDialog.setDirectory(initialPath);
QStringList mimeTypes;
const QList<QByteArray> baMimeTypes = QImageWriter::supportedMimeTypes();
for (const QByteArray &bf : baMimeTypes)
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()
{
QScreen *screen = QGuiApplication::primaryScreen();
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();
}
//! [4]
//! [6]
void Screenshot::updateCheckBox()
{
if (delaySpinBox->value() == 0) {
hideThisWindowCheckBox->setDisabled(true);
hideThisWindowCheckBox->setChecked(false);
} else {
hideThisWindowCheckBox->setDisabled(false);
}
}
//! [6]
//! [10]
void Screenshot::updateScreenshotLabel()
{
screenshotLabel->setPixmap(originalPixmap.scaled(screenshotLabel->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
//! [10]

View File

@ -0,0 +1,50 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef SCREENSHOT_H
#define SCREENSHOT_H
#include <QPixmap>
#include <QWidget>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QGridLayout;
class QGroupBox;
class QHBoxLayout;
class QLabel;
class QPushButton;
class QSpinBox;
class QVBoxLayout;
QT_END_NAMESPACE
//! [0]
class Screenshot : public QWidget
{
Q_OBJECT
public:
Screenshot();
protected:
void resizeEvent(QResizeEvent *event) override;
private slots:
void newScreenshot();
void saveScreenshot();
void shootScreen();
void updateCheckBox();
private:
void updateScreenshotLabel();
QPixmap originalPixmap;
QLabel *screenshotLabel;
QSpinBox *delaySpinBox;
QCheckBox *hideThisWindowCheckBox;
QPushButton *newScreenshotButton;
};
//! [0]
#endif // SCREENSHOT_H

View File

@ -0,0 +1,10 @@
QT += widgets
requires(qtConfig(filedialog))
HEADERS = screenshot.h
SOURCES = main.cpp \
screenshot.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/desktop/screenshot
INSTALLS += target

View File

@ -0,0 +1,51 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(systray LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/desktop/systray")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(systray
main.cpp
window.cpp window.h
)
set_target_properties(systray PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(systray PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
# Resources:
set(systray_resource_files
"images/bad.png"
"images/heart.png"
"images/trash.png"
)
qt_add_resources(systray "systray"
PREFIX
"/"
FILES
${systray_resource_files}
)
install(TARGETS systray
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

View File

@ -0,0 +1,163 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\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.
\borderedimage systemtray-example.png
\caption 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.
\borderedimage 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.
\macos users note: The Growl notification system must be
installed for QSystemTrayIcon::showMessage() to display messages.
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. We need to
avoid showing the message and accepting the close event when the
user really intends to quit the application: that is, when the
user has triggered "Quit" in the menu bar, or in the tray icon's
context menu, or pressed Command+Q shortcut on \macOS.
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 \c
{desktop/systray/window.cpp} file for details.
*/

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,49 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#ifndef QT_NO_SYSTEMTRAYICON
#include <QMessageBox>
#include "window.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(systray);
QApplication app(argc, argv);
if (!QSystemTrayIcon::isSystemTrayAvailable()) {
QMessageBox::critical(nullptr, QObject::tr("Systray"),
QObject::tr("I couldn't detect any system tray "
"on this system."));
return 1;
}
QApplication::setQuitOnLastWindowClosed(false);
Window window;
window.show();
return app.exec();
}
#else
#include <QLabel>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QString text("QSystemTrayIcon is not supported on this platform");
QLabel *label = new QLabel(text);
label->setWordWrap(true);
label->show();
qDebug() << text;
app.exec();
}
#endif

View File

@ -0,0 +1,11 @@
HEADERS = window.h
SOURCES = main.cpp \
window.cpp
RESOURCES = systray.qrc
QT += widgets
requires(qtConfig(combobox))
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/desktop/systray
INSTALLS += target

View File

@ -0,0 +1,7 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="/">
<file>images/bad.png</file>
<file>images/heart.png</file>
<file>images/trash.png</file>
</qresource>
</RCC>

View File

@ -0,0 +1,247 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "window.h"
#ifndef QT_NO_SYSTEMTRAYICON
#include <QAction>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QCloseEvent>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QPushButton>
#include <QSpinBox>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QMessageBox>
//! [0]
Window::Window()
{
createIconGroupBox();
createMessageGroupBox();
iconLabel->setMinimumWidth(durationLabel->sizeHint().width());
createActions();
createTrayIcon();
connect(showMessageButton, &QAbstractButton::clicked, this, &Window::showMessage);
connect(showIconCheckBox, &QAbstractButton::toggled, trayIcon, &QSystemTrayIcon::setVisible);
connect(iconComboBox, &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);
mainLayout->addWidget(messageGroupBox);
setLayout(mainLayout);
iconComboBox->setCurrentIndex(1);
trayIcon->show();
setWindowTitle(tr("Systray"));
resize(400, 300);
}
//! [0]
//! [1]
void Window::setVisible(bool visible)
{
minimizeAction->setEnabled(visible);
maximizeAction->setEnabled(!isMaximized());
restoreAction->setEnabled(isMaximized() || !visible);
QDialog::setVisible(visible);
}
//! [1]
//! [2]
void Window::closeEvent(QCloseEvent *event)
{
if (!event->spontaneous() || !isVisible())
return;
if (trayIcon->isVisible()) {
QMessageBox::information(this, tr("Systray"),
tr("The program will keep running in the "
"system tray. To terminate the program, "
"choose <b>Quit</b> in the context menu "
"of the system tray entry."));
hide();
event->ignore();
}
}
//! [2]
//! [3]
void Window::setIcon(int index)
{
QIcon icon = iconComboBox->itemIcon(index);
trayIcon->setIcon(icon);
setWindowIcon(icon);
trayIcon->setToolTip(iconComboBox->itemText(index));
}
//! [3]
//! [4]
void Window::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick:
iconComboBox->setCurrentIndex((iconComboBox->currentIndex() + 1) % iconComboBox->count());
break;
case QSystemTrayIcon::MiddleClick:
showMessage();
break;
default:
;
}
}
//! [4]
//! [5]
void Window::showMessage()
{
showIconCheckBox->setChecked(true);
int selectedIcon = typeComboBox->itemData(typeComboBox->currentIndex()).toInt();
QSystemTrayIcon::MessageIcon msgIcon = QSystemTrayIcon::MessageIcon(selectedIcon);
if (selectedIcon == -1) { // custom icon
QIcon icon(iconComboBox->itemIcon(iconComboBox->currentIndex()));
trayIcon->showMessage(titleEdit->text(), bodyEdit->toPlainText(), icon,
durationSpinBox->value() * 1000);
} else {
trayIcon->showMessage(titleEdit->text(), bodyEdit->toPlainText(), msgIcon,
durationSpinBox->value() * 1000);
}
}
//! [5]
//! [6]
void Window::messageClicked()
{
QMessageBox::information(nullptr, tr("Systray"),
tr("Sorry, I already gave what help I could.\n"
"Maybe you should try asking a human?"));
}
//! [6]
void Window::createIconGroupBox()
{
iconGroupBox = new QGroupBox(tr("Tray Icon"));
iconLabel = new QLabel("Icon:");
iconComboBox = new QComboBox;
iconComboBox->addItem(QIcon(":/images/bad.png"), tr("Bad"));
iconComboBox->addItem(QIcon(":/images/heart.png"), tr("Heart"));
iconComboBox->addItem(QIcon(":/images/trash.png"), tr("Trash"));
showIconCheckBox = new QCheckBox(tr("Show icon"));
showIconCheckBox->setChecked(true);
QHBoxLayout *iconLayout = new QHBoxLayout;
iconLayout->addWidget(iconLabel);
iconLayout->addWidget(iconComboBox);
iconLayout->addStretch();
iconLayout->addWidget(showIconCheckBox);
iconGroupBox->setLayout(iconLayout);
}
void Window::createMessageGroupBox()
{
messageGroupBox = new QGroupBox(tr("Balloon Message"));
typeLabel = new QLabel(tr("Type:"));
typeComboBox = new QComboBox;
typeComboBox->addItem(tr("None"), QSystemTrayIcon::NoIcon);
typeComboBox->addItem(style()->standardIcon(
QStyle::SP_MessageBoxInformation), tr("Information"),
QSystemTrayIcon::Information);
typeComboBox->addItem(style()->standardIcon(
QStyle::SP_MessageBoxWarning), tr("Warning"),
QSystemTrayIcon::Warning);
typeComboBox->addItem(style()->standardIcon(
QStyle::SP_MessageBoxCritical), tr("Critical"),
QSystemTrayIcon::Critical);
typeComboBox->addItem(QIcon(), tr("Custom icon"),
-1);
typeComboBox->setCurrentIndex(1);
durationLabel = new QLabel(tr("Duration:"));
durationSpinBox = new QSpinBox;
durationSpinBox->setRange(5, 60);
durationSpinBox->setSuffix(" s");
durationSpinBox->setValue(15);
durationWarningLabel = new QLabel(tr("(some systems might ignore this "
"hint)"));
durationWarningLabel->setIndent(10);
titleLabel = new QLabel(tr("Title:"));
titleEdit = new QLineEdit(tr("Cannot connect to network"));
bodyLabel = new QLabel(tr("Body:"));
bodyEdit = new QTextEdit;
bodyEdit->setPlainText(tr("Don't believe me. Honestly, I don't have a "
"clue.\nClick this balloon for details."));
showMessageButton = new QPushButton(tr("Show Message"));
showMessageButton->setDefault(true);
QGridLayout *messageLayout = new QGridLayout;
messageLayout->addWidget(typeLabel, 0, 0);
messageLayout->addWidget(typeComboBox, 0, 1, 1, 2);
messageLayout->addWidget(durationLabel, 1, 0);
messageLayout->addWidget(durationSpinBox, 1, 1);
messageLayout->addWidget(durationWarningLabel, 1, 2, 1, 3);
messageLayout->addWidget(titleLabel, 2, 0);
messageLayout->addWidget(titleEdit, 2, 1, 1, 4);
messageLayout->addWidget(bodyLabel, 3, 0);
messageLayout->addWidget(bodyEdit, 3, 1, 2, 4);
messageLayout->addWidget(showMessageButton, 5, 4);
messageLayout->setColumnStretch(3, 1);
messageLayout->setRowStretch(4, 1);
messageGroupBox->setLayout(messageLayout);
}
void Window::createActions()
{
minimizeAction = new QAction(tr("Mi&nimize"), this);
connect(minimizeAction, &QAction::triggered, this, &QWidget::hide);
maximizeAction = new QAction(tr("Ma&ximize"), this);
connect(maximizeAction, &QAction::triggered, this, &QWidget::showMaximized);
restoreAction = new QAction(tr("&Restore"), this);
connect(restoreAction, &QAction::triggered, this, &QWidget::showNormal);
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
}
void Window::createTrayIcon()
{
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(minimizeAction);
trayIconMenu->addAction(maximizeAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}
#endif

View File

@ -0,0 +1,80 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef WINDOW_H
#define WINDOW_H
#include <QSystemTrayIcon>
#ifndef QT_NO_SYSTEMTRAYICON
#include <QDialog>
QT_BEGIN_NAMESPACE
class QAction;
class QCheckBox;
class QComboBox;
class QGroupBox;
class QLabel;
class QLineEdit;
class QMenu;
class QPushButton;
class QSpinBox;
class QTextEdit;
QT_END_NAMESPACE
//! [0]
class Window : public QDialog
{
Q_OBJECT
public:
Window();
void setVisible(bool visible) override;
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void setIcon(int index);
void iconActivated(QSystemTrayIcon::ActivationReason reason);
void showMessage();
void messageClicked();
private:
void createIconGroupBox();
void createMessageGroupBox();
void createActions();
void createTrayIcon();
QGroupBox *iconGroupBox;
QLabel *iconLabel;
QComboBox *iconComboBox;
QCheckBox *showIconCheckBox;
QGroupBox *messageGroupBox;
QLabel *typeLabel;
QLabel *durationLabel;
QLabel *durationWarningLabel;
QLabel *titleLabel;
QLabel *bodyLabel;
QComboBox *typeComboBox;
QSpinBox *durationSpinBox;
QLineEdit *titleEdit;
QTextEdit *bodyEdit;
QPushButton *showMessageButton;
QAction *minimizeAction;
QAction *maximizeAction;
QAction *restoreAction;
QAction *quitAction;
QSystemTrayIcon *trayIcon;
QMenu *trayIconMenu;
};
//! [0]
#endif // QT_NO_SYSTEMTRAYICON
#endif

View File

@ -0,0 +1,13 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
if(QT_FEATURE_wizard)
qt_internal_add_example(classwizard)
qt_internal_add_example(trivialwizard)
endif()
qt_internal_add_example(extension)
qt_internal_add_example(standarddialogs)
qt_internal_add_example(tabdialog)
if(QT_FEATURE_wizard AND TARGET Qt6::PrintSupport)
qt_internal_add_example(licensewizard)
endif()

View File

@ -0,0 +1,9 @@
Qt includes standard dialogs for many common operations, such as file
selection, printing, and color selection.
Custom dialogs can also be created for specialized modal or modeless
interactions with users.
Documentation for these examples can be found via the Examples
link in the main Qt documentation.

View File

@ -0,0 +1,55 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(classwizard LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/dialogs/classwizard")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(classwizard
classwizard.cpp classwizard.h
main.cpp
)
set_target_properties(classwizard PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(classwizard PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
# Resources:
set(classwizard_resource_files
"images/background.png"
"images/banner.png"
"images/logo1.png"
"images/logo2.png"
"images/logo3.png"
"images/watermark1.png"
"images/watermark2.png"
)
qt_add_resources(classwizard "classwizard"
PREFIX
"/"
FILES
${classwizard_resource_files}
)
install(TARGETS classwizard
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,394 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "classwizard.h"
//! [0] //! [1]
ClassWizard::ClassWizard(QWidget *parent)
: QWizard(parent)
{
addPage(new IntroPage);
addPage(new ClassInfoPage);
addPage(new CodeStylePage);
addPage(new OutputFilesPage);
addPage(new ConclusionPage);
//! [0]
setPixmap(QWizard::BannerPixmap, QPixmap(":/images/banner.png"));
setPixmap(QWizard::BackgroundPixmap, QPixmap(":/images/background.png"));
setWindowTitle(tr("Class Wizard"));
//! [2]
}
//! [1] //! [2]
//! [3]
void ClassWizard::accept()
//! [3] //! [4]
{
QByteArray className = field("className").toByteArray();
QByteArray baseClass = field("baseClass").toByteArray();
QByteArray macroName = field("macroName").toByteArray();
QByteArray baseInclude = field("baseInclude").toByteArray();
QString outputDir = field("outputDir").toString();
QString header = field("header").toString();
QString implementation = field("implementation").toString();
//! [4]
QByteArray block;
if (field("comment").toBool()) {
block += "/*\n";
block += " " + header.toLatin1() + '\n';
block += "*/\n";
block += '\n';
}
if (field("protect").toBool()) {
block += "#ifndef " + macroName + '\n';
block += "#define " + macroName + '\n';
block += '\n';
}
if (field("includeBase").toBool()) {
block += "#include " + baseInclude + '\n';
block += '\n';
}
block += "class " + className;
if (!baseClass.isEmpty())
block += " : public " + baseClass;
block += '\n';
block += "{\n";
/* qmake ignore Q_OBJECT */
if (field("qobjectMacro").toBool()) {
block += " Q_OBJECT\n";
block += '\n';
}
block += "public:\n";
if (field("qobjectCtor").toBool()) {
block += " " + className + "(QObject *parent = nullptr);\n";
} else if (field("qwidgetCtor").toBool()) {
block += " " + className + "(QWidget *parent = nullptr);\n";
} else if (field("defaultCtor").toBool()) {
block += " " + className + "();\n";
if (field("copyCtor").toBool()) {
block += " " + className + "(const " + className + " &other);\n";
block += '\n';
block += " " + className + " &operator=" + "(const " + className
+ " &other);\n";
}
}
block += "};\n";
if (field("protect").toBool()) {
block += '\n';
block += "#endif\n";
}
QFile headerFile(outputDir + '/' + header);
if (!headerFile.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(nullptr, QObject::tr("Simple Wizard"),
QObject::tr("Cannot write file %1:\n%2")
.arg(headerFile.fileName())
.arg(headerFile.errorString()));
return;
}
headerFile.write(block);
block.clear();
if (field("comment").toBool()) {
block += "/*\n";
block += " " + implementation.toLatin1() + '\n';
block += "*/\n";
block += '\n';
}
block += "#include \"" + header.toLatin1() + "\"\n";
block += '\n';
if (field("qobjectCtor").toBool()) {
block += className + "::" + className + "(QObject *parent)\n";
block += " : " + baseClass + "(parent)\n";
block += "{\n";
block += "}\n";
} else if (field("qwidgetCtor").toBool()) {
block += className + "::" + className + "(QWidget *parent)\n";
block += " : " + baseClass + "(parent)\n";
block += "{\n";
block += "}\n";
} else if (field("defaultCtor").toBool()) {
block += className + "::" + className + "()\n";
block += "{\n";
block += " // missing code\n";
block += "}\n";
if (field("copyCtor").toBool()) {
block += "\n";
block += className + "::" + className + "(const " + className
+ " &other)\n";
block += "{\n";
block += " *this = other;\n";
block += "}\n";
block += '\n';
block += className + " &" + className + "::operator=(const "
+ className + " &other)\n";
block += "{\n";
if (!baseClass.isEmpty())
block += " " + baseClass + "::operator=(other);\n";
block += " // missing code\n";
block += " return *this;\n";
block += "}\n";
}
}
QFile implementationFile(outputDir + '/' + implementation);
if (!implementationFile.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(nullptr, QObject::tr("Simple Wizard"),
QObject::tr("Cannot write file %1:\n%2")
.arg(implementationFile.fileName())
.arg(implementationFile.errorString()));
return;
}
implementationFile.write(block);
//! [5]
QDialog::accept();
//! [5] //! [6]
}
//! [6]
//! [7]
IntroPage::IntroPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Introduction"));
setPixmap(QWizard::WatermarkPixmap, QPixmap(":/images/watermark1.png"));
label = new QLabel(tr("This wizard will generate a skeleton C++ class "
"definition, including a few functions. You simply "
"need to specify the class name and set a few "
"options to produce a header file and an "
"implementation file for your new C++ class."));
label->setWordWrap(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
setLayout(layout);
}
//! [7]
//! [8] //! [9]
ClassInfoPage::ClassInfoPage(QWidget *parent)
: QWizardPage(parent)
{
//! [8]
setTitle(tr("Class Information"));
setSubTitle(tr("Specify basic information about the class for which you "
"want to generate skeleton source code files."));
setPixmap(QWizard::LogoPixmap, QPixmap(":/images/logo1.png"));
//! [10]
classNameLabel = new QLabel(tr("&Class name:"));
classNameLineEdit = new QLineEdit;
classNameLabel->setBuddy(classNameLineEdit);
baseClassLabel = new QLabel(tr("B&ase class:"));
baseClassLineEdit = new QLineEdit;
baseClassLabel->setBuddy(baseClassLineEdit);
qobjectMacroCheckBox = new QCheckBox(tr("Generate Q_OBJECT &macro"));
//! [10]
groupBox = new QGroupBox(tr("C&onstructor"));
//! [9]
qobjectCtorRadioButton = new QRadioButton(tr("&QObject-style constructor"));
qwidgetCtorRadioButton = new QRadioButton(tr("Q&Widget-style constructor"));
defaultCtorRadioButton = new QRadioButton(tr("&Default constructor"));
copyCtorCheckBox = new QCheckBox(tr("&Generate copy constructor and "
"operator="));
defaultCtorRadioButton->setChecked(true);
connect(defaultCtorRadioButton, &QAbstractButton::toggled,
copyCtorCheckBox, &QWidget::setEnabled);
//! [11] //! [12]
registerField("className*", classNameLineEdit);
registerField("baseClass", baseClassLineEdit);
registerField("qobjectMacro", qobjectMacroCheckBox);
//! [11]
registerField("qobjectCtor", qobjectCtorRadioButton);
registerField("qwidgetCtor", qwidgetCtorRadioButton);
registerField("defaultCtor", defaultCtorRadioButton);
registerField("copyCtor", copyCtorCheckBox);
QVBoxLayout *groupBoxLayout = new QVBoxLayout;
//! [12]
groupBoxLayout->addWidget(qobjectCtorRadioButton);
groupBoxLayout->addWidget(qwidgetCtorRadioButton);
groupBoxLayout->addWidget(defaultCtorRadioButton);
groupBoxLayout->addWidget(copyCtorCheckBox);
groupBox->setLayout(groupBoxLayout);
QGridLayout *layout = new QGridLayout;
layout->addWidget(classNameLabel, 0, 0);
layout->addWidget(classNameLineEdit, 0, 1);
layout->addWidget(baseClassLabel, 1, 0);
layout->addWidget(baseClassLineEdit, 1, 1);
layout->addWidget(qobjectMacroCheckBox, 2, 0, 1, 2);
layout->addWidget(groupBox, 3, 0, 1, 2);
setLayout(layout);
//! [13]
}
//! [13]
//! [14]
CodeStylePage::CodeStylePage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Code Style Options"));
setSubTitle(tr("Choose the formatting of the generated code."));
setPixmap(QWizard::LogoPixmap, QPixmap(":/images/logo2.png"));
commentCheckBox = new QCheckBox(tr("&Start generated files with a "
//! [14]
"comment"));
commentCheckBox->setChecked(true);
protectCheckBox = new QCheckBox(tr("&Protect header file against multiple "
"inclusions"));
protectCheckBox->setChecked(true);
macroNameLabel = new QLabel(tr("&Macro name:"));
macroNameLineEdit = new QLineEdit;
macroNameLabel->setBuddy(macroNameLineEdit);
includeBaseCheckBox = new QCheckBox(tr("&Include base class definition"));
baseIncludeLabel = new QLabel(tr("Base class include:"));
baseIncludeLineEdit = new QLineEdit;
baseIncludeLabel->setBuddy(baseIncludeLineEdit);
connect(protectCheckBox, &QAbstractButton::toggled,
macroNameLabel, &QWidget::setEnabled);
connect(protectCheckBox, &QAbstractButton::toggled,
macroNameLineEdit, &QWidget::setEnabled);
connect(includeBaseCheckBox, &QAbstractButton::toggled,
baseIncludeLabel, &QWidget::setEnabled);
connect(includeBaseCheckBox, &QAbstractButton::toggled,
baseIncludeLineEdit, &QWidget::setEnabled);
registerField("comment", commentCheckBox);
registerField("protect", protectCheckBox);
registerField("macroName", macroNameLineEdit);
registerField("includeBase", includeBaseCheckBox);
registerField("baseInclude", baseIncludeLineEdit);
QGridLayout *layout = new QGridLayout;
layout->setColumnMinimumWidth(0, 20);
layout->addWidget(commentCheckBox, 0, 0, 1, 3);
layout->addWidget(protectCheckBox, 1, 0, 1, 3);
layout->addWidget(macroNameLabel, 2, 1);
layout->addWidget(macroNameLineEdit, 2, 2);
layout->addWidget(includeBaseCheckBox, 3, 0, 1, 3);
layout->addWidget(baseIncludeLabel, 4, 1);
layout->addWidget(baseIncludeLineEdit, 4, 2);
//! [15]
setLayout(layout);
}
//! [15]
//! [16]
void CodeStylePage::initializePage()
{
QString className = field("className").toString();
macroNameLineEdit->setText(className.toUpper() + "_H");
QString baseClass = field("baseClass").toString();
includeBaseCheckBox->setChecked(!baseClass.isEmpty());
includeBaseCheckBox->setEnabled(!baseClass.isEmpty());
baseIncludeLabel->setEnabled(!baseClass.isEmpty());
baseIncludeLineEdit->setEnabled(!baseClass.isEmpty());
QRegularExpression rx("Q[A-Z].*");
if (baseClass.isEmpty()) {
baseIncludeLineEdit->clear();
} else if (rx.match(baseClass).hasMatch()) {
baseIncludeLineEdit->setText('<' + baseClass + '>');
} else {
baseIncludeLineEdit->setText('"' + baseClass.toLower() + ".h\"");
}
}
//! [16]
OutputFilesPage::OutputFilesPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Output Files"));
setSubTitle(tr("Specify where you want the wizard to put the generated "
"skeleton code."));
setPixmap(QWizard::LogoPixmap, QPixmap(":/images/logo3.png"));
outputDirLabel = new QLabel(tr("&Output directory:"));
outputDirLineEdit = new QLineEdit;
outputDirLabel->setBuddy(outputDirLineEdit);
headerLabel = new QLabel(tr("&Header file name:"));
headerLineEdit = new QLineEdit;
headerLabel->setBuddy(headerLineEdit);
implementationLabel = new QLabel(tr("&Implementation file name:"));
implementationLineEdit = new QLineEdit;
implementationLabel->setBuddy(implementationLineEdit);
registerField("outputDir*", outputDirLineEdit);
registerField("header*", headerLineEdit);
registerField("implementation*", implementationLineEdit);
QGridLayout *layout = new QGridLayout;
layout->addWidget(outputDirLabel, 0, 0);
layout->addWidget(outputDirLineEdit, 0, 1);
layout->addWidget(headerLabel, 1, 0);
layout->addWidget(headerLineEdit, 1, 1);
layout->addWidget(implementationLabel, 2, 0);
layout->addWidget(implementationLineEdit, 2, 1);
setLayout(layout);
}
//! [17]
void OutputFilesPage::initializePage()
{
QString className = field("className").toString();
headerLineEdit->setText(className.toLower() + ".h");
implementationLineEdit->setText(className.toLower() + ".cpp");
outputDirLineEdit->setText(QDir::toNativeSeparators(QDir::tempPath()));
}
//! [17]
ConclusionPage::ConclusionPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Conclusion"));
setPixmap(QWizard::WatermarkPixmap, QPixmap(":/images/watermark2.png"));
label = new QLabel;
label->setWordWrap(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
setLayout(layout);
}
void ConclusionPage::initializePage()
{
QString finishText = wizard()->buttonText(QWizard::FinishButton);
finishText.remove('&');
label->setText(tr("Click %1 to generate the class skeleton.")
.arg(finishText));
}

View File

@ -0,0 +1,119 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef CLASSWIZARD_H
#define CLASSWIZARD_H
#include <QWizard>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QGroupBox;
class QLabel;
class QLineEdit;
class QRadioButton;
QT_END_NAMESPACE
//! [0]
class ClassWizard : public QWizard
{
Q_OBJECT
public:
ClassWizard(QWidget *parent = nullptr);
void accept() override;
};
//! [0]
//! [1]
class IntroPage : public QWizardPage
{
Q_OBJECT
public:
IntroPage(QWidget *parent = nullptr);
private:
QLabel *label;
};
//! [1]
//! [2]
class ClassInfoPage : public QWizardPage
{
Q_OBJECT
public:
ClassInfoPage(QWidget *parent = nullptr);
private:
QLabel *classNameLabel;
QLabel *baseClassLabel;
QLineEdit *classNameLineEdit;
QLineEdit *baseClassLineEdit;
QCheckBox *qobjectMacroCheckBox;
QGroupBox *groupBox;
QRadioButton *qobjectCtorRadioButton;
QRadioButton *qwidgetCtorRadioButton;
QRadioButton *defaultCtorRadioButton;
QCheckBox *copyCtorCheckBox;
};
//! [2]
//! [3]
class CodeStylePage : public QWizardPage
{
Q_OBJECT
public:
CodeStylePage(QWidget *parent = nullptr);
protected:
void initializePage() override;
private:
QCheckBox *commentCheckBox;
QCheckBox *protectCheckBox;
QCheckBox *includeBaseCheckBox;
QLabel *macroNameLabel;
QLabel *baseIncludeLabel;
QLineEdit *macroNameLineEdit;
QLineEdit *baseIncludeLineEdit;
};
//! [3]
class OutputFilesPage : public QWizardPage
{
Q_OBJECT
public:
OutputFilesPage(QWidget *parent = nullptr);
protected:
void initializePage() override;
private:
QLabel *outputDirLabel;
QLabel *headerLabel;
QLabel *implementationLabel;
QLineEdit *outputDirLineEdit;
QLineEdit *headerLineEdit;
QLineEdit *implementationLineEdit;
};
class ConclusionPage : public QWizardPage
{
Q_OBJECT
public:
ConclusionPage(QWidget *parent = nullptr);
protected:
void initializePage() override;
private:
QLabel *label;
};
#endif

View File

@ -0,0 +1,10 @@
QT += widgets
HEADERS = classwizard.h
SOURCES = classwizard.cpp \
main.cpp
RESOURCES = classwizard.qrc
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/dialogs/classwizard
INSTALLS += target

View File

@ -0,0 +1,11 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/background.png</file>
<file>images/banner.png</file>
<file>images/logo1.png</file>
<file>images/logo2.png</file>
<file>images/logo3.png</file>
<file>images/watermark1.png</file>
<file>images/watermark2.png</file>
</qresource>
</RCC>

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,28 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
#include "classwizard.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(classwizard);
QApplication app(argc, argv);
#ifndef QT_NO_TRANSLATION
QString translatorFileName = QLatin1String("qtbase_");
translatorFileName += QLocale::system().name();
QTranslator *translator = new QTranslator(&app);
if (translator->load(translatorFileName, QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
app.installTranslator(translator);
#endif
ClassWizard wizard;
wizard.show();
return app.exec();
}

View File

@ -0,0 +1,14 @@
QT_FOR_CONFIG += widgets
TEMPLATE = subdirs
SUBDIRS = classwizard \
extension \
licensewizard \
standarddialogs \
tabdialog \
trivialwizard
!qtHaveModule(printsupport): SUBDIRS -= licensewizard
!qtConfig(wizard) {
SUBDIRS -= trivialwizard licensewizard classwizard
}

View File

@ -0,0 +1,37 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(extension LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/dialogs/extension")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(extension
finddialog.cpp finddialog.h
main.cpp
)
set_target_properties(extension PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(extension PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS extension
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,9 @@
QT += widgets
HEADERS = finddialog.h
SOURCES = finddialog.cpp \
main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/dialogs/extension
INSTALLS += target

View File

@ -0,0 +1,77 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "finddialog.h"
//! [0]
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);
caseCheckBox = new QCheckBox(tr("Match &case"));
fromStartCheckBox = new QCheckBox(tr("Search from &start"));
fromStartCheckBox->setChecked(true);
//! [1]
findButton = new QPushButton(tr("&Find"));
findButton->setDefault(true);
moreButton = new QPushButton(tr("&More"));
moreButton->setCheckable(true);
//! [0]
moreButton->setAutoDefault(false);
//! [1]
//! [2]
extension = new QWidget;
wholeWordsCheckBox = new QCheckBox(tr("&Whole words"));
backwardCheckBox = new QCheckBox(tr("Search &backward"));
searchSelectionCheckBox = new QCheckBox(tr("Search se&lection"));
//! [2]
//! [3]
buttonBox = new QDialogButtonBox(Qt::Vertical);
buttonBox->addButton(findButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(moreButton, QDialogButtonBox::ActionRole);
connect(moreButton, &QAbstractButton::toggled, extension, &QWidget::setVisible);
QVBoxLayout *extensionLayout = new QVBoxLayout;
extensionLayout->setContentsMargins(QMargins());
extensionLayout->addWidget(wholeWordsCheckBox);
extensionLayout->addWidget(backwardCheckBox);
extensionLayout->addWidget(searchSelectionCheckBox);
extension->setLayout(extensionLayout);
//! [3]
//! [4]
QHBoxLayout *topLeftLayout = new QHBoxLayout;
topLeftLayout->addWidget(label);
topLeftLayout->addWidget(lineEdit);
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout(topLeftLayout);
leftLayout->addWidget(caseCheckBox);
leftLayout->addWidget(fromStartCheckBox);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
mainLayout->addLayout(leftLayout, 0, 0);
mainLayout->addWidget(buttonBox, 0, 1);
mainLayout->addWidget(extension, 1, 0, 1, 2);
mainLayout->setRowStretch(2, 1);
setLayout(mainLayout);
setWindowTitle(tr("Extension"));
//! [4] //! [5]
extension->hide();
}
//! [5]

View File

@ -0,0 +1,41 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QDialogButtonBox;
class QGroupBox;
class QLabel;
class QLineEdit;
class QPushButton;
QT_END_NAMESPACE
//! [0]
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = nullptr);
private:
QLabel *label;
QLineEdit *lineEdit;
QCheckBox *caseCheckBox;
QCheckBox *fromStartCheckBox;
QCheckBox *wholeWordsCheckBox;
QCheckBox *searchSelectionCheckBox;
QCheckBox *backwardCheckBox;
QDialogButtonBox *buttonBox;
QPushButton *findButton;
QPushButton *moreButton;
QWidget *extension;
};
//! [0]
#endif

View File

@ -0,0 +1,16 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include "finddialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
FindDialog dialog;
dialog.show();
return app.exec();
}

View File

@ -0,0 +1,51 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(licensewizard LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/dialogs/licensewizard")
find_package(Qt6 REQUIRED COMPONENTS Core Gui PrintSupport Widgets)
qt_standard_project_setup()
qt_add_executable(licensewizard
licensewizard.cpp licensewizard.h
main.cpp
)
set_target_properties(licensewizard PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(licensewizard PRIVATE
Qt6::Core
Qt6::Gui
Qt6::PrintSupport
Qt6::Widgets
)
# Resources:
set(licensewizard_resource_files
"images/logo.png"
"images/watermark.png"
)
qt_add_resources(licensewizard "licensewizard"
PREFIX
"/"
FILES
${licensewizard_resource_files}
)
install(TARGETS licensewizard
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File

@ -0,0 +1,333 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printdialog)
#include <QPrinter>
#include <QPrintDialog>
#endif
#endif
#include "licensewizard.h"
QString emailRegExp = QStringLiteral(".+@.+");
//! [0] //! [1] //! [2]
LicenseWizard::LicenseWizard(QWidget *parent)
: QWizard(parent)
{
//! [0]
setPage(Page_Intro, new IntroPage);
setPage(Page_Evaluate, new EvaluatePage);
setPage(Page_Register, new RegisterPage);
setPage(Page_Details, new DetailsPage);
setPage(Page_Conclusion, new ConclusionPage);
//! [1]
setStartId(Page_Intro);
//! [2]
//! [3]
#ifndef Q_OS_MAC
//! [3] //! [4]
setWizardStyle(ModernStyle);
#endif
//! [4] //! [5]
setOption(HaveHelpButton, true);
//! [5] //! [6]
setPixmap(QWizard::LogoPixmap, QPixmap(":/images/logo.png"));
//! [7]
connect(this, &QWizard::helpRequested, this, &LicenseWizard::showHelp);
//! [7]
setWindowTitle(tr("License Wizard"));
//! [8]
}
//! [6] //! [8]
//! [9] //! [10]
void LicenseWizard::showHelp()
//! [9] //! [11]
{
static QString lastHelpMessage;
QString message;
switch (currentId()) {
case Page_Intro:
message = tr("The decision you make here will affect which page you "
"get to see next.");
break;
//! [10] //! [11]
case Page_Evaluate:
message = tr("Make sure to provide a valid email address, such as "
"toni.buddenbrook@example.de.");
break;
case Page_Register:
message = tr("If you don't provide an upgrade key, you will be "
"asked to fill in your details.");
break;
case Page_Details:
message = tr("Make sure to provide a valid email address, such as "
"thomas.gradgrind@example.co.uk.");
break;
case Page_Conclusion:
message = tr("You must accept the terms and conditions of the "
"license to proceed.");
break;
//! [12] //! [13]
default:
message = tr("This help is likely not to be of any help.");
}
//! [12]
if (lastHelpMessage == message)
message = tr("Sorry, I already gave what help I could. "
"Maybe you should try asking a human?");
//! [14]
QMessageBox::information(this, tr("License Wizard Help"), message);
//! [14]
lastHelpMessage = message;
//! [15]
}
//! [13] //! [15]
//! [16]
IntroPage::IntroPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Introduction"));
setPixmap(QWizard::WatermarkPixmap, QPixmap(":/images/watermark.png"));
topLabel = new QLabel(tr("This wizard will help you register your copy of "
"<i>Super Product One</i>&trade; or start "
"evaluating the product."));
topLabel->setWordWrap(true);
registerRadioButton = new QRadioButton(tr("&Register your copy"));
evaluateRadioButton = new QRadioButton(tr("&Evaluate the product for 30 "
"days"));
registerRadioButton->setChecked(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(topLabel);
layout->addWidget(registerRadioButton);
layout->addWidget(evaluateRadioButton);
setLayout(layout);
}
//! [16] //! [17]
//! [18]
int IntroPage::nextId() const
//! [17] //! [19]
{
if (evaluateRadioButton->isChecked()) {
return LicenseWizard::Page_Evaluate;
} else {
return LicenseWizard::Page_Register;
}
}
//! [18] //! [19]
//! [20]
EvaluatePage::EvaluatePage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Evaluate <i>Super Product One</i>&trade;"));
setSubTitle(tr("Please fill both fields. Make sure to provide a valid "
"email address (e.g., john.smith@example.com)."));
nameLabel = new QLabel(tr("N&ame:"));
nameLineEdit = new QLineEdit;
//! [20]
nameLabel->setBuddy(nameLineEdit);
emailLabel = new QLabel(tr("&Email address:"));
emailLineEdit = new QLineEdit;
emailLineEdit->setValidator(new QRegularExpressionValidator(QRegularExpression(emailRegExp), this));
emailLabel->setBuddy(emailLineEdit);
//! [21]
registerField("evaluate.name*", nameLineEdit);
registerField("evaluate.email*", emailLineEdit);
//! [21]
QGridLayout *layout = new QGridLayout;
layout->addWidget(nameLabel, 0, 0);
layout->addWidget(nameLineEdit, 0, 1);
layout->addWidget(emailLabel, 1, 0);
layout->addWidget(emailLineEdit, 1, 1);
setLayout(layout);
//! [22]
}
//! [22]
//! [23]
int EvaluatePage::nextId() const
{
return LicenseWizard::Page_Conclusion;
}
//! [23]
RegisterPage::RegisterPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Register Your Copy of <i>Super Product One</i>&trade;"));
setSubTitle(tr("If you have an upgrade key, please fill in "
"the appropriate field."));
nameLabel = new QLabel(tr("N&ame:"));
nameLineEdit = new QLineEdit;
nameLabel->setBuddy(nameLineEdit);
upgradeKeyLabel = new QLabel(tr("&Upgrade key:"));
upgradeKeyLineEdit = new QLineEdit;
upgradeKeyLabel->setBuddy(upgradeKeyLineEdit);
registerField("register.name*", nameLineEdit);
registerField("register.upgradeKey", upgradeKeyLineEdit);
QGridLayout *layout = new QGridLayout;
layout->addWidget(nameLabel, 0, 0);
layout->addWidget(nameLineEdit, 0, 1);
layout->addWidget(upgradeKeyLabel, 1, 0);
layout->addWidget(upgradeKeyLineEdit, 1, 1);
setLayout(layout);
}
//! [24]
int RegisterPage::nextId() const
{
if (upgradeKeyLineEdit->text().isEmpty()) {
return LicenseWizard::Page_Details;
} else {
return LicenseWizard::Page_Conclusion;
}
}
//! [24]
DetailsPage::DetailsPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Fill In Your Details"));
setSubTitle(tr("Please fill all three fields. Make sure to provide a valid "
"email address (e.g., tanaka.aya@example.co.jp)."));
companyLabel = new QLabel(tr("&Company name:"));
companyLineEdit = new QLineEdit;
companyLabel->setBuddy(companyLineEdit);
emailLabel = new QLabel(tr("&Email address:"));
emailLineEdit = new QLineEdit;
emailLineEdit->setValidator(new QRegularExpressionValidator(QRegularExpression(emailRegExp), this));
emailLabel->setBuddy(emailLineEdit);
postalLabel = new QLabel(tr("&Postal address:"));
postalLineEdit = new QLineEdit;
postalLabel->setBuddy(postalLineEdit);
registerField("details.company*", companyLineEdit);
registerField("details.email*", emailLineEdit);
registerField("details.postal*", postalLineEdit);
QGridLayout *layout = new QGridLayout;
layout->addWidget(companyLabel, 0, 0);
layout->addWidget(companyLineEdit, 0, 1);
layout->addWidget(emailLabel, 1, 0);
layout->addWidget(emailLineEdit, 1, 1);
layout->addWidget(postalLabel, 2, 0);
layout->addWidget(postalLineEdit, 2, 1);
setLayout(layout);
}
//! [25]
int DetailsPage::nextId() const
{
return LicenseWizard::Page_Conclusion;
}
//! [25]
ConclusionPage::ConclusionPage(QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Complete Your Registration"));
setPixmap(QWizard::WatermarkPixmap, QPixmap(":/images/watermark.png"));
bottomLabel = new QLabel;
bottomLabel->setWordWrap(true);
agreeCheckBox = new QCheckBox(tr("I agree to the terms of the license"));
registerField("conclusion.agree*", agreeCheckBox);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(bottomLabel);
layout->addWidget(agreeCheckBox);
setLayout(layout);
}
//! [26]
int ConclusionPage::nextId() const
{
return -1;
}
//! [26]
//! [27]
void ConclusionPage::initializePage()
{
QString licenseText;
if (wizard()->hasVisitedPage(LicenseWizard::Page_Evaluate)) {
licenseText = tr("<u>Evaluation License Agreement:</u> "
"You can use this software for 30 days and make one "
"backup, but you are not allowed to distribute it.");
} else if (wizard()->hasVisitedPage(LicenseWizard::Page_Details)) {
licenseText = tr("<u>First-Time License Agreement:</u> "
"You can use this software subject to the license "
"you will receive by email.");
} else {
licenseText = tr("<u>Upgrade License Agreement:</u> "
"This software is licensed under the terms of your "
"current license.");
}
bottomLabel->setText(licenseText);
}
//! [27]
//! [28]
void ConclusionPage::setVisible(bool visible)
{
QWizardPage::setVisible(visible);
if (visible) {
//! [29]
wizard()->setButtonText(QWizard::CustomButton1, tr("&Print"));
wizard()->setOption(QWizard::HaveCustomButton1, true);
connect(wizard(), &QWizard::customButtonClicked,
this, &ConclusionPage::printButtonClicked);
//! [29]
} else {
wizard()->setOption(QWizard::HaveCustomButton1, false);
disconnect(wizard(), &QWizard::customButtonClicked,
this, &ConclusionPage::printButtonClicked);
}
}
//! [28]
void ConclusionPage::printButtonClicked()
{
#if defined(QT_PRINTSUPPORT_LIB) && QT_CONFIG(printdialog)
QPrinter printer;
QPrintDialog dialog(&printer, this);
if (dialog.exec())
QMessageBox::warning(this, tr("Print License"),
tr("As an environmentally friendly measure, the "
"license text will not actually be printed."));
#endif
}

View File

@ -0,0 +1,126 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef LICENSEWIZARD_H
#define LICENSEWIZARD_H
#include <QWizard>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QLabel;
class QLineEdit;
class QRadioButton;
QT_END_NAMESPACE
//! [0] //! [1]
class LicenseWizard : public QWizard
{
//! [0]
Q_OBJECT
public:
//! [2]
enum { Page_Intro, Page_Evaluate, Page_Register, Page_Details,
Page_Conclusion };
//! [2]
LicenseWizard(QWidget *parent = nullptr);
private slots:
void showHelp();
//! [3]
};
//! [1] //! [3]
//! [4]
class IntroPage : public QWizardPage
{
Q_OBJECT
public:
IntroPage(QWidget *parent = nullptr);
int nextId() const override;
private:
QLabel *topLabel;
QRadioButton *registerRadioButton;
QRadioButton *evaluateRadioButton;
};
//! [4]
//! [5]
class EvaluatePage : public QWizardPage
{
Q_OBJECT
public:
EvaluatePage(QWidget *parent = nullptr);
int nextId() const override;
private:
QLabel *nameLabel;
QLabel *emailLabel;
QLineEdit *nameLineEdit;
QLineEdit *emailLineEdit;
};
//! [5]
class RegisterPage : public QWizardPage
{
Q_OBJECT
public:
RegisterPage(QWidget *parent = nullptr);
int nextId() const override;
private:
QLabel *nameLabel;
QLabel *upgradeKeyLabel;
QLineEdit *nameLineEdit;
QLineEdit *upgradeKeyLineEdit;
};
class DetailsPage : public QWizardPage
{
Q_OBJECT
public:
DetailsPage(QWidget *parent = nullptr);
int nextId() const override;
private:
QLabel *companyLabel;
QLabel *emailLabel;
QLabel *postalLabel;
QLineEdit *companyLineEdit;
QLineEdit *emailLineEdit;
QLineEdit *postalLineEdit;
};
//! [6]
class ConclusionPage : public QWizardPage
{
Q_OBJECT
public:
ConclusionPage(QWidget *parent = nullptr);
void initializePage() override;
int nextId() const override;
void setVisible(bool visible) override;
private slots:
void printButtonClicked();
private:
QLabel *bottomLabel;
QCheckBox *agreeCheckBox;
};
//! [6]
#endif

View File

@ -0,0 +1,10 @@
QT += widgets printsupport
HEADERS = licensewizard.h
SOURCES = licensewizard.cpp \
main.cpp
RESOURCES = licensewizard.qrc
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/dialogs/licensewizard
INSTALLS += target

View File

@ -0,0 +1,6 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/logo.png</file>
<file>images/watermark.png</file>
</qresource>
</RCC>

View File

@ -0,0 +1,28 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
#include "licensewizard.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(licensewizard);
QApplication app(argc, argv);
#ifndef QT_NO_TRANSLATION
QString translatorFileName = QLatin1String("qtbase_");
translatorFileName += QLocale::system().name();
QTranslator *translator = new QTranslator(&app);
if (translator->load(translatorFileName, QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
app.installTranslator(translator);
#endif
LicenseWizard wizard;
wizard.show();
return app.exec();
}

View File

@ -0,0 +1,37 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(standarddialogs LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/dialogs/standarddialogs")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(standarddialogs
dialog.cpp dialog.h
main.cpp
)
set_target_properties(standarddialogs PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(standarddialogs PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS standarddialogs
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,479 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "dialog.h"
class DialogOptionsWidget : public QGroupBox
{
public:
explicit DialogOptionsWidget(QWidget *parent = nullptr);
void addCheckBox(const QString &text, int value);
void addSpacer();
int value() const;
private:
typedef QPair<QCheckBox *, int> CheckBoxEntry;
QVBoxLayout *layout;
QList<CheckBoxEntry> checkBoxEntries;
};
DialogOptionsWidget::DialogOptionsWidget(QWidget *parent) :
QGroupBox(parent) , layout(new QVBoxLayout)
{
setTitle(Dialog::tr("Options"));
setLayout(layout);
}
void DialogOptionsWidget::addCheckBox(const QString &text, int value)
{
QCheckBox *checkBox = new QCheckBox(text);
layout->addWidget(checkBox);
checkBoxEntries.append(CheckBoxEntry(checkBox, value));
}
void DialogOptionsWidget::addSpacer()
{
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
}
int DialogOptionsWidget::value() const
{
int result = 0;
for (const CheckBoxEntry &checkboxEntry : std::as_const(checkBoxEntries)) {
if (checkboxEntry.first->isChecked())
result |= checkboxEntry.second;
}
return result;
}
Dialog::Dialog(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *verticalLayout;
if (QGuiApplication::styleHints()->showIsFullScreen() || QGuiApplication::styleHints()->showIsMaximized()) {
QHBoxLayout *horizontalLayout = new QHBoxLayout(this);
QGroupBox *groupBox = new QGroupBox(QGuiApplication::applicationDisplayName(), this);
horizontalLayout->addWidget(groupBox);
verticalLayout = new QVBoxLayout(groupBox);
} else {
verticalLayout = new QVBoxLayout(this);
}
QToolBox *toolbox = new QToolBox;
verticalLayout->addWidget(toolbox);
errorMessageDialog = new QErrorMessage(this);
int frameStyle = QFrame::Sunken | QFrame::Panel;
integerLabel = new QLabel;
integerLabel->setFrameStyle(frameStyle);
QPushButton *integerButton =
new QPushButton(tr("QInputDialog::get&Int()"));
doubleLabel = new QLabel;
doubleLabel->setFrameStyle(frameStyle);
QPushButton *doubleButton =
new QPushButton(tr("QInputDialog::get&Double()"));
itemLabel = new QLabel;
itemLabel->setFrameStyle(frameStyle);
QPushButton *itemButton = new QPushButton(tr("QInputDialog::getIte&m()"));
textLabel = new QLabel;
textLabel->setFrameStyle(frameStyle);
QPushButton *textButton = new QPushButton(tr("QInputDialog::get&Text()"));
multiLineTextLabel = new QLabel;
multiLineTextLabel->setFrameStyle(frameStyle);
QPushButton *multiLineTextButton = new QPushButton(tr("QInputDialog::get&MultiLineText()"));
colorLabel = new QLabel;
colorLabel->setFrameStyle(frameStyle);
QPushButton *colorButton = new QPushButton(tr("QColorDialog::get&Color()"));
fontLabel = new QLabel;
fontLabel->setFrameStyle(frameStyle);
QPushButton *fontButton = new QPushButton(tr("QFontDialog::get&Font()"));
directoryLabel = new QLabel;
directoryLabel->setFrameStyle(frameStyle);
QPushButton *directoryButton =
new QPushButton(tr("QFileDialog::getE&xistingDirectory()"));
openFileNameLabel = new QLabel;
openFileNameLabel->setFrameStyle(frameStyle);
QPushButton *openFileNameButton =
new QPushButton(tr("QFileDialog::get&OpenFileName()"));
openFileNamesLabel = new QLabel;
openFileNamesLabel->setFrameStyle(frameStyle);
QPushButton *openFileNamesButton =
new QPushButton(tr("QFileDialog::&getOpenFileNames()"));
saveFileNameLabel = new QLabel;
saveFileNameLabel->setFrameStyle(frameStyle);
QPushButton *saveFileNameButton =
new QPushButton(tr("QFileDialog::get&SaveFileName()"));
criticalLabel = new QLabel;
criticalLabel->setFrameStyle(frameStyle);
QPushButton *criticalButton =
new QPushButton(tr("QMessageBox::critica&l()"));
informationLabel = new QLabel;
informationLabel->setFrameStyle(frameStyle);
QPushButton *informationButton =
new QPushButton(tr("QMessageBox::i&nformation()"));
questionLabel = new QLabel;
questionLabel->setFrameStyle(frameStyle);
QPushButton *questionButton =
new QPushButton(tr("QMessageBox::&question()"));
warningLabel = new QLabel;
warningLabel->setFrameStyle(frameStyle);
QPushButton *warningButton = new QPushButton(tr("QMessageBox::&warning()"));
QPushButton *errorButton =
new QPushButton(tr("QErrorMessage::showM&essage()"));
connect(integerButton, &QAbstractButton::clicked, this, &Dialog::setInteger);
connect(doubleButton, &QAbstractButton::clicked, this, &Dialog::setDouble);
connect(itemButton, &QAbstractButton::clicked, this, &Dialog::setItem);
connect(textButton, &QAbstractButton::clicked, this, &Dialog::setText);
connect(multiLineTextButton, &QAbstractButton::clicked, this, &Dialog::setMultiLineText);
connect(colorButton, &QAbstractButton::clicked, this, &Dialog::setColor);
connect(fontButton, &QAbstractButton::clicked, this, &Dialog::setFont);
connect(directoryButton, &QAbstractButton::clicked,
this, &Dialog::setExistingDirectory);
connect(openFileNameButton, &QAbstractButton::clicked,
this, &Dialog::setOpenFileName);
connect(openFileNamesButton, &QAbstractButton::clicked,
this, &Dialog::setOpenFileNames);
connect(saveFileNameButton, &QAbstractButton::clicked,
this, &Dialog::setSaveFileName);
connect(criticalButton, &QAbstractButton::clicked, this, &Dialog::criticalMessage);
connect(informationButton, &QAbstractButton::clicked,
this, &Dialog::informationMessage);
connect(questionButton, &QAbstractButton::clicked, this, &Dialog::questionMessage);
connect(warningButton, &QAbstractButton::clicked, this, &Dialog::warningMessage);
connect(errorButton, &QAbstractButton::clicked, this, &Dialog::errorMessage);
QWidget *page = new QWidget;
QGridLayout *layout = new QGridLayout(page);
layout->setColumnStretch(1, 1);
layout->setColumnMinimumWidth(1, 250);
layout->addWidget(integerButton, 0, 0);
layout->addWidget(integerLabel, 0, 1);
layout->addWidget(doubleButton, 1, 0);
layout->addWidget(doubleLabel, 1, 1);
layout->addWidget(itemButton, 2, 0);
layout->addWidget(itemLabel, 2, 1);
layout->addWidget(textButton, 3, 0);
layout->addWidget(textLabel, 3, 1);
layout->addWidget(multiLineTextButton, 4, 0);
layout->addWidget(multiLineTextLabel, 4, 1);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 5, 0);
toolbox->addItem(page, tr("Input Dialogs"));
const QString doNotUseNativeDialog = tr("Do not use native dialog");
page = new QWidget;
layout = new QGridLayout(page);
layout->setColumnStretch(1, 1);
layout->addWidget(colorButton, 0, 0);
layout->addWidget(colorLabel, 0, 1);
colorDialogOptionsWidget = new DialogOptionsWidget;
colorDialogOptionsWidget->addCheckBox(doNotUseNativeDialog, QColorDialog::DontUseNativeDialog);
colorDialogOptionsWidget->addCheckBox(tr("Show alpha channel") , QColorDialog::ShowAlphaChannel);
colorDialogOptionsWidget->addCheckBox(tr("No buttons") , QColorDialog::NoButtons);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 1, 0);
layout->addWidget(colorDialogOptionsWidget, 2, 0, 1 ,2);
toolbox->addItem(page, tr("Color Dialog"));
page = new QWidget;
layout = new QGridLayout(page);
layout->setColumnStretch(1, 1);
layout->addWidget(fontButton, 0, 0);
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);
toolbox->addItem(page, tr("Font Dialog"));
page = new QWidget;
layout = new QGridLayout(page);
layout->setColumnStretch(1, 1);
layout->addWidget(directoryButton, 0, 0);
layout->addWidget(directoryLabel, 0, 1);
layout->addWidget(openFileNameButton, 1, 0);
layout->addWidget(openFileNameLabel, 1, 1);
layout->addWidget(openFileNamesButton, 2, 0);
layout->addWidget(openFileNamesLabel, 2, 1);
layout->addWidget(saveFileNameButton, 3, 0);
layout->addWidget(saveFileNameLabel, 3, 1);
fileDialogOptionsWidget = new DialogOptionsWidget;
fileDialogOptionsWidget->addCheckBox(doNotUseNativeDialog, QFileDialog::DontUseNativeDialog);
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("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"));
page = new QWidget;
layout = new QGridLayout(page);
layout->setColumnStretch(1, 1);
layout->addWidget(criticalButton, 0, 0);
layout->addWidget(criticalLabel, 0, 1);
layout->addWidget(informationButton, 1, 0);
layout->addWidget(informationLabel, 1, 1);
layout->addWidget(questionButton, 2, 0);
layout->addWidget(questionLabel, 2, 1);
layout->addWidget(warningButton, 3, 0);
layout->addWidget(warningLabel, 3, 1);
layout->addWidget(errorButton, 4, 0);
layout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding), 5, 0);
toolbox->addItem(page, tr("Message Boxes"));
setWindowTitle(QGuiApplication::applicationDisplayName());
}
void Dialog::setInteger()
{
//! [0]
bool ok;
int i = QInputDialog::getInt(this, tr("QInputDialog::getInt()"),
tr("Percentage:"), 25, 0, 100, 1, &ok);
if (ok)
integerLabel->setText(tr("%1%").arg(i));
//! [0]
}
void Dialog::setDouble()
{
//! [1]
bool ok;
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
tr("Amount:"), 37.56, -10000, 10000, 2, &ok,
Qt::WindowFlags(), 1);
if (ok)
doubleLabel->setText(QString("$%1").arg(d));
//! [1]
}
void Dialog::setItem()
{
//! [2]
QStringList items;
items << tr("Spring") << tr("Summer") << tr("Fall") << tr("Winter");
bool ok;
QString item = QInputDialog::getItem(this, tr("QInputDialog::getItem()"),
tr("Season:"), items, 0, false, &ok);
if (ok && !item.isEmpty())
itemLabel->setText(item);
//! [2]
}
void Dialog::setText()
{
//! [3]
bool ok;
QString text = QInputDialog::getText(this, tr("QInputDialog::getText()"),
tr("User name:"), QLineEdit::Normal,
QDir::home().dirName(), &ok);
if (ok && !text.isEmpty())
textLabel->setText(text);
//! [3]
}
void Dialog::setMultiLineText()
{
//! [4]
bool ok;
QString text = QInputDialog::getMultiLineText(this, tr("QInputDialog::getMultiLineText()"),
tr("Address:"), "John Doe\nFreedom Street", &ok);
if (ok && !text.isEmpty())
multiLineTextLabel->setText(text);
//! [4]
}
void Dialog::setColor()
{
const QColorDialog::ColorDialogOptions options = QFlag(colorDialogOptionsWidget->value());
const QColor color = QColorDialog::getColor(Qt::green, this, "Select Color", options);
if (color.isValid()) {
colorLabel->setText(color.name());
colorLabel->setPalette(QPalette(color));
colorLabel->setAutoFillBackground(true);
}
}
void Dialog::setFont()
{
const QFontDialog::FontDialogOptions options = QFlag(fontDialogOptionsWidget->value());
const QString &description = fontLabel->text();
QFont defaultFont;
if (!description.isEmpty())
defaultFont.fromString(description);
bool ok;
QFont font = QFontDialog::getFont(&ok, defaultFont, this, "Select Font", options);
if (ok) {
fontLabel->setText(font.key());
fontLabel->setFont(font);
}
}
void Dialog::setExistingDirectory()
{
QFileDialog::Options options = QFlag(fileDialogOptionsWidget->value());
options |= QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly;
QString directory = QFileDialog::getExistingDirectory(this,
tr("QFileDialog::getExistingDirectory()"),
directoryLabel->text(),
options);
if (!directory.isEmpty())
directoryLabel->setText(directory);
}
void Dialog::setOpenFileName()
{
const QFileDialog::Options options = QFlag(fileDialogOptionsWidget->value());
QString selectedFilter;
QString fileName = QFileDialog::getOpenFileName(this,
tr("QFileDialog::getOpenFileName()"),
openFileNameLabel->text(),
tr("All Files (*);;Text Files (*.txt)"),
&selectedFilter,
options);
if (!fileName.isEmpty())
openFileNameLabel->setText(fileName);
}
void Dialog::setOpenFileNames()
{
const QFileDialog::Options options = QFlag(fileDialogOptionsWidget->value());
QString selectedFilter;
QStringList files = QFileDialog::getOpenFileNames(
this, tr("QFileDialog::getOpenFileNames()"),
openFilesPath,
tr("All Files (*);;Text Files (*.txt)"),
&selectedFilter,
options);
if (files.count()) {
openFilesPath = files[0];
openFileNamesLabel->setText(QString("[%1]").arg(files.join(", ")));
}
}
void Dialog::setSaveFileName()
{
const QFileDialog::Options options = QFlag(fileDialogOptionsWidget->value());
QString selectedFilter;
QString fileName = QFileDialog::getSaveFileName(this,
tr("QFileDialog::getSaveFileName()"),
saveFileNameLabel->text(),
tr("All Files (*);;Text Files (*.txt)"),
&selectedFilter,
options);
if (!fileName.isEmpty())
saveFileNameLabel->setText(fileName);
}
void Dialog::criticalMessage()
{
QMessageBox msgBox(QMessageBox::Critical, tr("QMessageBox::critical()"),
tr("Houston, we have a problem"), { }, this);
msgBox.setInformativeText(tr("Activating the liquid oxygen stirring fans caused an explosion in one of the tanks. " \
"Liquid oxygen levels are getting low. This may jeopardize the moon landing mission."));
msgBox.addButton(QMessageBox::Abort);
msgBox.addButton(QMessageBox::Retry);
msgBox.addButton(QMessageBox::Ignore);
int reply = msgBox.exec();
if (reply == QMessageBox::Abort)
criticalLabel->setText(tr("Abort"));
else if (reply == QMessageBox::Retry)
criticalLabel->setText(tr("Retry"));
else
criticalLabel->setText(tr("Ignore"));
}
void Dialog::informationMessage()
{
QMessageBox msgBox(QMessageBox::Information, tr("QMessageBox::information()"),
tr("Elvis has left the building."), { }, this);
msgBox.setInformativeText(tr("This phrase was often used by public address announcers at the conclusion " \
"of Elvis Presley concerts in order to disperse audiences who lingered in " \
"hopes of an encore. It has since become a catchphrase and punchline."));
if (msgBox.exec() == QMessageBox::Ok)
informationLabel->setText(tr("OK"));
else
informationLabel->setText(tr("Escape"));
}
void Dialog::questionMessage()
{
QMessageBox msgBox(QMessageBox::Question, tr("QMessageBox::question()"),
tr("Would you like cheese with that?"), { }, this);
msgBox.setInformativeText(tr("A cheeseburger is a hamburger topped with cheese. Traditionally, the slice of " \
"cheese is placed on top of the meat patty. The cheese is usually added to the " \
"cooking hamburger patty shortly before serving, which allows the cheese to melt."));
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.addButton(QMessageBox::Cancel);
int reply = msgBox.exec();
if (reply == QMessageBox::Yes)
questionLabel->setText(tr("Yes"));
else if (reply == QMessageBox::No)
questionLabel->setText(tr("No"));
else
questionLabel->setText(tr("Cancel"));
}
void Dialog::warningMessage()
{
QMessageBox msgBox(QMessageBox::Warning, tr("QMessageBox::warning()"),
tr("Delete the only copy of your movie manuscript?"), { }, this);
msgBox.setInformativeText(tr("You've been working on this manuscript for 738 days now. Hang in there!"));
msgBox.setDetailedText("\"A long time ago in a galaxy far, far away....\"");
msgBox.addButton(tr("&Keep"), QMessageBox::AcceptRole);
msgBox.addButton(tr("Delete"), QMessageBox::DestructiveRole);
if (msgBox.exec() == QMessageBox::AcceptRole)
warningLabel->setText(tr("Keep"));
else
warningLabel->setText(tr("Delete"));
}
void Dialog::errorMessage()
{
errorMessageDialog->showMessage(
tr("This dialog shows and remembers error messages. "
"If the user chooses to not show the dialog again, the dialog "
"will not appear again if QErrorMessage::showMessage() "
"is called with the same message."));
errorMessageDialog->showMessage(
tr("You can queue up error messages, and they will be "
"shown one after each other. Each message maintains "
"its own state for whether it will be shown again "
"the next time QErrorMessage::showMessage() is called "
"with the same message."));
}

View File

@ -0,0 +1,65 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef DIALOG_H
#define DIALOG_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QLabel;
class QErrorMessage;
QT_END_NAMESPACE
class DialogOptionsWidget;
class Dialog : public QWidget
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
private slots:
void setInteger();
void setDouble();
void setItem();
void setText();
void setMultiLineText();
void setColor();
void setFont();
void setExistingDirectory();
void setOpenFileName();
void setOpenFileNames();
void setSaveFileName();
void criticalMessage();
void informationMessage();
void questionMessage();
void warningMessage();
void errorMessage();
private:
QLabel *integerLabel;
QLabel *doubleLabel;
QLabel *itemLabel;
QLabel *textLabel;
QLabel *multiLineTextLabel;
QLabel *colorLabel;
QLabel *fontLabel;
QLabel *directoryLabel;
QLabel *openFileNameLabel;
QLabel *openFileNamesLabel;
QLabel *saveFileNameLabel;
QLabel *criticalLabel;
QLabel *informationLabel;
QLabel *questionLabel;
QLabel *warningLabel;
QErrorMessage *errorMessageDialog;
DialogOptionsWidget *fileDialogOptionsWidget;
DialogOptionsWidget *colorDialogOptionsWidget;
DialogOptionsWidget *fontDialogOptionsWidget;
QString openFilesPath;
};
#endif

View File

@ -0,0 +1,39 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QScreen>
#include <QStyleHints>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
#include "dialog.h"
using namespace Qt::StringLiterals;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#if QT_CONFIG(translation)
QTranslator translator;
if (translator.load(QLocale::system(), u"qtbase"_s, u"_"_s,
QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
app.installTranslator(&translator);
}
#endif
QGuiApplication::setApplicationDisplayName(Dialog::tr("Standard Dialogs"));
Dialog dialog;
if (!QGuiApplication::styleHints()->showIsFullScreen() && !QGuiApplication::styleHints()->showIsMaximized()) {
const QRect availableGeometry = dialog.screen()->availableGeometry();
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();
}

View File

@ -0,0 +1,47 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QScreen>
#include <QStyleHints>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
#include "dialog.h"
#include <AppKit/AppKit.h>
using namespace Qt::StringLiterals;
int main(int argc, char *argv[])
{
[NSApplication sharedApplication];
NSApplicationLoad();
NSApplicationLoad();
[NSApp run];
QApplication app(argc, argv);
//app.setAttribute(Qt::AA_DontUseNativeDialogs);
#if QT_CONFIG(translation)
QTranslator translator;
if (translator.load(QLocale::system(), u"qtbase"_s, u"_"_s,
QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
app.installTranslator(&translator);
}
#endif
QGuiApplication::setApplicationDisplayName(Dialog::tr("Standard Dialogs"));
Dialog dialog;
if (!QGuiApplication::styleHints()->showIsFullScreen() && !QGuiApplication::styleHints()->showIsMaximized()) {
const QRect availableGeometry = dialog.screen()->availableGeometry();
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();
}

View File

@ -0,0 +1,10 @@
QT += widgets
requires(qtConfig(filedialog))
HEADERS = dialog.h
SOURCES = dialog.cpp \
main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/dialogs/standarddialogs
INSTALLS += target

View File

@ -0,0 +1,37 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(tabdialog LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/dialogs/tabdialog")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(tabdialog
main.cpp
tabdialog.cpp tabdialog.h
)
set_target_properties(tabdialog PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(tabdialog PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS tabdialog
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,22 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include "tabdialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QString fileName;
if (argc >= 2)
fileName = argv[1];
else
fileName = ".";
TabDialog tabdialog(fileName);
tabdialog.show();
return app.exec();
}

View File

@ -0,0 +1,158 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "tabdialog.h"
//! [0]
TabDialog::TabDialog(const QString &fileName, QWidget *parent)
: QDialog(parent)
{
QFileInfo fileInfo(fileName);
tabWidget = new QTabWidget;
tabWidget->addTab(new GeneralTab(fileInfo), tr("General"));
tabWidget->addTab(new PermissionsTab(fileInfo), tr("Permissions"));
tabWidget->addTab(new ApplicationsTab(fileInfo), tr("Applications"));
//! [0]
//! [1] //! [2]
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
//! [1] //! [3]
| QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
//! [2] //! [3]
//! [4]
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(tabWidget);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
//! [4]
//! [5]
setWindowTitle(tr("Tab Dialog"));
}
//! [5]
//! [6]
GeneralTab::GeneralTab(const QFileInfo &fileInfo, QWidget *parent)
: QWidget(parent)
{
QLabel *fileNameLabel = new QLabel(tr("File Name:"));
QLineEdit *fileNameEdit = new QLineEdit(fileInfo.fileName());
QLabel *pathLabel = new QLabel(tr("Path:"));
QLabel *pathValueLabel = new QLabel(fileInfo.absoluteFilePath());
pathValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
QLabel *sizeLabel = new QLabel(tr("Size:"));
qlonglong size = fileInfo.size()/1024;
QLabel *sizeValueLabel = new QLabel(tr("%1 K").arg(size));
sizeValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
QLabel *lastReadLabel = new QLabel(tr("Last Read:"));
QLabel *lastReadValueLabel = new QLabel(fileInfo.lastRead().toString());
lastReadValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
QLabel *lastModLabel = new QLabel(tr("Last Modified:"));
QLabel *lastModValueLabel = new QLabel(fileInfo.lastModified().toString());
lastModValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(fileNameLabel);
mainLayout->addWidget(fileNameEdit);
mainLayout->addWidget(pathLabel);
mainLayout->addWidget(pathValueLabel);
mainLayout->addWidget(sizeLabel);
mainLayout->addWidget(sizeValueLabel);
mainLayout->addWidget(lastReadLabel);
mainLayout->addWidget(lastReadValueLabel);
mainLayout->addWidget(lastModLabel);
mainLayout->addWidget(lastModValueLabel);
mainLayout->addStretch(1);
setLayout(mainLayout);
}
//! [6]
//! [7]
PermissionsTab::PermissionsTab(const QFileInfo &fileInfo, QWidget *parent)
: QWidget(parent)
{
QGroupBox *permissionsGroup = new QGroupBox(tr("Permissions"));
QCheckBox *readable = new QCheckBox(tr("Readable"));
if (fileInfo.isReadable())
readable->setChecked(true);
QCheckBox *writable = new QCheckBox(tr("Writable"));
if ( fileInfo.isWritable() )
writable->setChecked(true);
QCheckBox *executable = new QCheckBox(tr("Executable"));
if ( fileInfo.isExecutable() )
executable->setChecked(true);
QGroupBox *ownerGroup = new QGroupBox(tr("Ownership"));
QLabel *ownerLabel = new QLabel(tr("Owner"));
QLabel *ownerValueLabel = new QLabel(fileInfo.owner());
ownerValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
QLabel *groupLabel = new QLabel(tr("Group"));
QLabel *groupValueLabel = new QLabel(fileInfo.group());
groupValueLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
QVBoxLayout *permissionsLayout = new QVBoxLayout;
permissionsLayout->addWidget(readable);
permissionsLayout->addWidget(writable);
permissionsLayout->addWidget(executable);
permissionsGroup->setLayout(permissionsLayout);
QVBoxLayout *ownerLayout = new QVBoxLayout;
ownerLayout->addWidget(ownerLabel);
ownerLayout->addWidget(ownerValueLabel);
ownerLayout->addWidget(groupLabel);
ownerLayout->addWidget(groupValueLabel);
ownerGroup->setLayout(ownerLayout);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(permissionsGroup);
mainLayout->addWidget(ownerGroup);
mainLayout->addStretch(1);
setLayout(mainLayout);
}
//! [7]
//! [8]
ApplicationsTab::ApplicationsTab(const QFileInfo &fileInfo, QWidget *parent)
: QWidget(parent)
{
QLabel *topLabel = new QLabel(tr("Open with:"));
QListWidget *applicationsListBox = new QListWidget;
QStringList applications;
for (int i = 1; i <= 30; ++i)
applications.append(tr("Application %1").arg(i));
applicationsListBox->insertItems(0, applications);
QCheckBox *alwaysCheckBox;
if (fileInfo.suffix().isEmpty())
alwaysCheckBox = new QCheckBox(tr("Always use this application to "
"open this type of file"));
else
alwaysCheckBox = new QCheckBox(tr("Always use this application to "
"open files with the extension '%1'").arg(fileInfo.suffix()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(topLabel);
layout->addWidget(applicationsListBox);
layout->addWidget(alwaysCheckBox);
setLayout(layout);
}
//! [8]

View File

@ -0,0 +1,62 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef TABDIALOG_H
#define TABDIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
class QDialogButtonBox;
class QFileInfo;
class QTabWidget;
QT_END_NAMESPACE
//! [0]
class GeneralTab : public QWidget
{
Q_OBJECT
public:
explicit GeneralTab(const QFileInfo &fileInfo, QWidget *parent = nullptr);
};
//! [0]
//! [1]
class PermissionsTab : public QWidget
{
Q_OBJECT
public:
explicit PermissionsTab(const QFileInfo &fileInfo, QWidget *parent = nullptr);
};
//! [1]
//! [2]
class ApplicationsTab : public QWidget
{
Q_OBJECT
public:
explicit ApplicationsTab(const QFileInfo &fileInfo, QWidget *parent = nullptr);
};
//! [2]
//! [3]
class TabDialog : public QDialog
{
Q_OBJECT
public:
explicit TabDialog(const QString &fileName, QWidget *parent = nullptr);
private:
QTabWidget *tabWidget;
QDialogButtonBox *buttonBox;
};
//! [3]
#endif

View File

@ -0,0 +1,10 @@
QT += widgets
requires(qtConfig(listwidget))
HEADERS = tabdialog.h
SOURCES = main.cpp \
tabdialog.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/dialogs/tabdialog
INSTALLS += target

View File

@ -0,0 +1,36 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(trivialwizard LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/dialogs/trivialwizard")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(trivialwizard
trivialwizard.cpp
)
set_target_properties(trivialwizard PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(trivialwizard PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS trivialwizard
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,99 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
//! [0] //! [1]
QWizardPage *createIntroPage()
{
QWizardPage *page = new QWizardPage;
page->setTitle("Introduction");
QLabel *label = new QLabel("This wizard will help you register your copy "
"of Super Product Two.");
label->setWordWrap(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
page->setLayout(layout);
return page;
}
//! [0]
//! [2]
QWizardPage *createRegistrationPage()
//! [1] //! [3]
{
//! [3]
QWizardPage *page = new QWizardPage;
page->setTitle("Registration");
page->setSubTitle("Please fill both fields.");
QLabel *nameLabel = new QLabel("Name:");
QLineEdit *nameLineEdit = new QLineEdit;
QLabel *emailLabel = new QLabel("Email address:");
QLineEdit *emailLineEdit = new QLineEdit;
QGridLayout *layout = new QGridLayout;
layout->addWidget(nameLabel, 0, 0);
layout->addWidget(nameLineEdit, 0, 1);
layout->addWidget(emailLabel, 1, 0);
layout->addWidget(emailLineEdit, 1, 1);
page->setLayout(layout);
return page;
//! [4]
}
//! [2] //! [4]
//! [5] //! [6]
QWizardPage *createConclusionPage()
//! [5] //! [7]
{
//! [7]
QWizardPage *page = new QWizardPage;
page->setTitle("Conclusion");
QLabel *label = new QLabel("You are now successfully registered. Have a "
"nice day!");
label->setWordWrap(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
page->setLayout(layout);
return page;
//! [8]
}
//! [6] //! [8]
//! [9] //! [10]
int main(int argc, char *argv[])
//! [9] //! [11]
{
QApplication app(argc, argv);
#ifndef QT_NO_TRANSLATION
QString translatorFileName = QLatin1String("qtbase_");
translatorFileName += QLocale::system().name();
QTranslator *translator = new QTranslator(&app);
if (translator->load(translatorFileName, QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
app.installTranslator(translator);
#endif
QWizard wizard;
wizard.addPage(createIntroPage());
wizard.addPage(createRegistrationPage());
wizard.addPage(createConclusionPage());
wizard.setWindowTitle("Trivial Wizard");
wizard.show();
return app.exec();
}
//! [10] //! [11]

View File

@ -0,0 +1,7 @@
QT += widgets
SOURCES = trivialwizard.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/dialogs/trivialwizard
INSTALLS += target

View File

@ -0,0 +1,222 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\example draganddrop/dropsite
\title Drop Site Example
\brief The example shows how to distinguish the various MIME formats available
in a drag and drop operation.
\image dropsite-example.png Screenshot of the Drop Site example
The Drop Site example accepts drops from other applications, and displays
the MIME formats provided by the drag object.
There are two classes, \c DropArea and \c DropSiteWindow, and a \c main()
function in this example. A \c DropArea object is instantiated in
\c DropSiteWindow; a \c DropSiteWindow object is then invoked in the
\c main() function.
\section1 DropArea Class Definition
The \c DropArea class is a subclass of QLabel with a public slot,
\c clear(), and a \c changed() signal.
\snippet draganddrop/dropsite/droparea.h DropArea header part1
In addition, \c DropArea contains reimplementations of four \l{QWidget}
event handlers:
\list 1
\li \l{QWidget::dragEnterEvent()}{dragEnterEvent()}
\li \l{QWidget::dragMoveEvent()}{dragMoveEvent()}
\li \l{QWidget::dragLeaveEvent()}{dragLeaveEvent()}
\li \l{QWidget::dropEvent()}{dropEvent()}
\endlist
These event handlers are further explained in the implementation of the
\c DropArea class.
\snippet draganddrop/dropsite/droparea.h DropArea header part2
\section1 DropArea Class Implementation
In the \c DropArea constructor, we set the \l{QWidget::setMinimumSize()}
{minimum size} to 200x200 pixels, the \l{QFrame::setFrameStyle()}
{frame style} to both QFrame::Sunken and QFrame::StyledPanel, and we align
its contents to the center.
\snippet draganddrop/dropsite/droparea.cpp DropArea constructor
Also, we enable drop events in \c DropArea by setting the
\l{QWidget::acceptDrops()}{acceptDrops} property to \c true. Then,
we enable the \l{QWidget::autoFillBackground()}{autoFillBackground}
property and invoke the \c clear() function.
The \l{QWidget::dragEnterEvent()}{dragEnterEvent()} event handler is
called when a drag is in progress and the mouse enters the \c DropArea
object. For the \c DropSite example, when the mouse enters \c DropArea,
we set its text to "<drop content>" and highlight its background.
\snippet draganddrop/dropsite/droparea.cpp dragEnterEvent() function
Then, we invoke \l{QDropEvent::acceptProposedAction()}
{acceptProposedAction()} on \a event, setting the drop action to the one
proposed. Lastly, we emit the \c changed() signal, with the data that was
dropped and its MIME type information as a parameter.
For \l{QWidget::dragMoveEvent()}{dragMoveEvent()}, we just accept the
proposed QDragMoveEvent object, \a event, with
\l{QDropEvent::acceptProposedAction()}{acceptProposedAction()}.
\snippet draganddrop/dropsite/droparea.cpp dragMoveEvent() function
The \c DropArea class's implementation of \l{QWidget::dropEvent()}
{dropEvent()} extracts the \a{event}'s mime data and displays it
accordingly.
\snippet draganddrop/dropsite/droparea.cpp dropEvent() function part1
The \c mimeData object can contain one of the following objects: an image,
HTML text, Markdown text, plain text, or a list of URLs.
\snippet draganddrop/dropsite/droparea.cpp dropEvent() function part2
\list
\li If \c mimeData contains an image, we display it in \c DropArea with
\l{QLabel::setPixmap()}{setPixmap()}.
\li If \c mimeData contains HTML, we display it with
\l{QLabel::setText()}{setText()} and set \c{DropArea}'s text format
as Qt::RichText.
\li If \c mimeData contains Markdown, we display it with
\l{QLabel::setText()}{setText()} and set \c{DropArea}'s text format
as Qt::MarkdownText.
\li If \c mimeData contains plain text, we display it with
\l{QLabel::setText()}{setText()} and set \c{DropArea}'s text format
as Qt::PlainText. In the event that \c mimeData contains URLs, we
iterate through the list of URLs to display them on individual
lines.
\li If \c mimeData contains other types of objects, we set
\c{DropArea}'s text, with \l{QLabel::setText()}{setText()} to
"Cannot display data" to inform the user.
\endlist
We then set \c{DropArea}'s \l{QWidget::backgroundRole()}{backgroundRole} to
QPalette::Dark and we accept \c{event}'s proposed action.
\snippet draganddrop/dropsite/droparea.cpp dropEvent() function part3
The \l{QWidget::dragLeaveEvent()}{dragLeaveEvent()} event handler is
called when a drag is in progress and the mouse leaves the widget.
\snippet draganddrop/dropsite/droparea.cpp dragLeaveEvent() function
For \c{DropArea}'s implementation, we clear invoke \c clear() and then
accept the proposed event.
The \c clear() function sets the text in \c DropArea to "<drop content>"
and sets the \l{QWidget::backgroundRole()}{backgroundRole} to
QPalette::Dark. Lastly, it emits the \c changed() signal.
\snippet draganddrop/dropsite/droparea.cpp clear() function
\section1 DropSiteWindow Class Definition
The \c DropSiteWindow class contains a constructor and a public slot,
\c updateFormatsTable().
\snippet draganddrop/dropsite/dropsitewindow.h DropSiteWindow header
The class also contains a private instance of \c DropArea, \c dropArea,
QLabel, \c abstractLabel, QTableWidget, \c formatsTable, QDialogButtonBox,
\c buttonBox, and two QPushButton objects, \c clearButton and
\c quitButton.
\section1 DropSiteWindow Class Implementation
In the constructor of \c DropSiteWindow, we instantiate \c abstractLabel
and set its \l{QLabel::setWordWrap()}{wordWrap} property to \c true. We
also call the \l{QLabel::adjustSize()}{adjustSize()} function to adjust
\c{abstractLabel}'s size according to its contents.
\snippet draganddrop/dropsite/dropsitewindow.cpp constructor part1
Then we instantiate \c dropArea and connect its \c changed() signal to
\c{DropSiteWindow}'s \c updateFormatsTable() slot.
\snippet draganddrop/dropsite/dropsitewindow.cpp constructor part2
We now set up the QTableWidget object, \c formatsTable. Its
horizontal header is set using a QStringList object, \c labels. The number
of columms are set to two and the table is not editable. Also, the
\c{formatTable}'s horizontal header is formatted to ensure that its second
column stretches to occupy additional space available.
\snippet draganddrop/dropsite/dropsitewindow.cpp constructor part3
Three QPushButton objects, \c clearButton, \c copyButton, and \c quitButton,
are instantiated and added to \c buttonBox - a QDialogButtonBox object. We
use QDialogButtonBox here to ensure that the push buttons are presented in a
layout that conforms to the platform's style.
\snippet draganddrop/dropsite/dropsitewindow.cpp constructor part4
The \l{QPushButton::clicked()}{clicked()} signals for \c copyButton,
\c clearButton, and \c quitButton are connected to \c copy(),
\c clear() and \l{QWidget::close()}{close()}, respectively.
For the layout, we use a QVBoxLayout, \c mainLayout, to arrange our widgets
vertically. We also set the window title to "Drop Site" and the minimum
size to 350x500 pixels.
\snippet draganddrop/dropsite/dropsitewindow.cpp constructor part5
We move on to the \c updateFormatsTable() function. This function updates
the \c formatsTable, displaying the MIME formats of the object dropped onto
the \c DropArea object. First, we set \l{QTableWidget}'s
\l{QTableWidget::setRowCount()}{rowCount} property to 0. Then, we validate
to ensure that the QMimeData object passed in is a valid object.
\snippet draganddrop/dropsite/dropsitewindow.cpp updateFormatsTable() part1
Once we are sure that \c mimeData is valid, we iterate through its
supported formats.
\note The \l{QMimeData::formats()}{formats()} function returns a
QStringList object, containing all the formats supported by the
\c mimeData.
\snippet draganddrop/dropsite/dropsitewindow.cpp updateFormatsTable() part2
Within each iteration, we create a QTableWidgetItem, \c formatItem and we
set its \l{QTableWidgetItem::setFlags()}{flags} to Qt::ItemIsEnabled, and
its \l{QTableWidgetItem::setTextAlignment()}{text alignment} to Qt::AlignTop
and Qt::AlignLeft.
A QString object, \c text, is customized to display data according to the
contents of \c format. We invoke \l{QString}'s \l{QString::simplified()}
{simplified()} function on \c text, to obtain a string that has no
additional space before, after or in between words.
\snippet draganddrop/dropsite/dropsitewindow.cpp updateFormatsTable() part3
If \c format contains a list of URLs, we iterate through them, using spaces
to separate them. On the other hand, if \c format contains an image, we
display the data by converting the text to hexadecimal.
\snippet draganddrop/dropsite/dropsitewindow.cpp updateFormatsTable() part4
Once \c text has been customized to contain the appropriate data, we insert
both \c format and \c text into \c formatsTable with
\l{QTableWidget::setItem()}{setItem()}. Lastly, we invoke
\l{QTableView::resizeColumnToContents()}{resizeColumnToContents()} on
\c{formatsTable}'s first column.
\section1 The main() Function
Within the \c main() function, we instantiate \c DropSiteWindow and invoke
its \l{QWidget::show()}{show()} function.
\snippet draganddrop/dropsite/main.cpp main() function
*/

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

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