diff options
Diffstat (limited to 'examples/sql')
64 files changed, 735 insertions, 694 deletions
diff --git a/examples/sql/CMakeLists.txt b/examples/sql/CMakeLists.txt index ce1014a06a..06d7d532d7 100644 --- a/examples/sql/CMakeLists.txt +++ b/examples/sql/CMakeLists.txt @@ -1,5 +1,5 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause if(NOT TARGET Qt6::Widgets) return() diff --git a/examples/sql/books/CMakeLists.txt b/examples/sql/books/CMakeLists.txt index 86ca051c3b..3fff917163 100644 --- a/examples/sql/books/CMakeLists.txt +++ b/examples/sql/books/CMakeLists.txt @@ -1,22 +1,16 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(books LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/books") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() qt_add_executable(books bookdelegate.cpp bookdelegate.h - bookwindow.cpp bookwindow.h bookwindow.ui + bookwindow.cpp bookwindow.h initdb.h main.cpp ) @@ -35,7 +29,8 @@ target_link_libraries(books PRIVATE # Resources: set(books_resource_files - "images/star.png" + "images/star.svg" + "images/star-filled.svg" ) qt_add_resources(books "books" @@ -46,7 +41,14 @@ qt_add_resources(books "books" ) install(TARGETS books - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET books + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/books/bookdelegate.cpp b/examples/sql/books/bookdelegate.cpp index af2a284298..ead9f9e7db 100644 --- a/examples/sql/books/bookdelegate.cpp +++ b/examples/sql/books/bookdelegate.cpp @@ -3,15 +3,13 @@ #include "bookdelegate.h" -#include <QtWidgets> +#include <QMouseEvent> +#include <QPainter> +#include <QSpinBox> -BookDelegate::BookDelegate(QObject *parent) - : QSqlRelationalDelegate(parent), star(QPixmap(":images/star.png")) -{ -} - -void BookDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const +void BookDelegate::paint(QPainter *painter, + const QStyleOptionViewItem &option, + const QModelIndex &index) const { if (index.column() != 5) { QSqlRelationalDelegate::paint(painter, option, index); @@ -28,31 +26,33 @@ void BookDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, option.rect, option.palette.color(cg, QPalette::Highlight)); - int rating = model->data(index, Qt::DisplayRole).toInt(); - int width = star.width(); - int height = star.height(); - int x = option.rect.x(); + const int rating = model->data(index, Qt::DisplayRole).toInt(); + const int width = iconDimension; + const int height = width; + // add cellPadding / 2 to center the stars in the cell + int x = option.rect.x() + cellPadding / 2; int y = option.rect.y() + (option.rect.height() / 2) - (height / 2); - for (int i = 0; i < rating; ++i) { - painter->drawPixmap(x, y, star); + + QIcon starIcon(QStringLiteral(":images/star.svg")); + QIcon starFilledIcon(QStringLiteral(":images/star-filled.svg")); + + for (int i = 0; i < 5; ++i) { + if (i < rating) + starFilledIcon.paint(painter, QRect(x, y, width, height)); + else + starIcon.paint(painter, QRect(x, y, width, height)); x += width; } } - - QPen pen = painter->pen(); - painter->setPen(option.palette.color(QPalette::Mid)); - painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); - painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); - painter->setPen(pen); } QSize BookDelegate::sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const + const QModelIndex &index) const { if (index.column() == 5) - return QSize(5 * star.width(), star.height()) + QSize(1, 1); + return QSize(5 * iconDimension, iconDimension) + QSize(cellPadding, cellPadding); // Since we draw the grid ourselves: - return QSqlRelationalDelegate::sizeHint(option, index) + QSize(1, 1); + return QSqlRelationalDelegate::sizeHint(option, index) + QSize(cellPadding, cellPadding); } bool BookDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, @@ -64,8 +64,8 @@ bool BookDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); - int stars = qBound(0, int(0.7 + qreal(mouseEvent->position().toPoint().x() - - option.rect.x()) / star.width()), 5); + int stars = qBound(0, int(0.7 + qreal(mouseEvent->position().x() + - option.rect.x()) / iconDimension), 5); model->setData(index, QVariant(stars)); // So that the selection can change: return false; diff --git a/examples/sql/books/bookdelegate.h b/examples/sql/books/bookdelegate.h index d0b157b395..b36cb371ac 100644 --- a/examples/sql/books/bookdelegate.h +++ b/examples/sql/books/bookdelegate.h @@ -5,7 +5,6 @@ #define BOOKDELEGATE_H #include <QModelIndex> -#include <QPixmap> #include <QSize> #include <QSqlRelationalDelegate> @@ -14,7 +13,7 @@ QT_FORWARD_DECLARE_CLASS(QPainter) class BookDelegate : public QSqlRelationalDelegate { public: - BookDelegate(QObject *parent); + using QSqlRelationalDelegate::QSqlRelationalDelegate; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; @@ -30,7 +29,8 @@ public: const QModelIndex &index) const override; private: - QPixmap star; + const int cellPadding = 6; + const int iconDimension = 24; }; #endif diff --git a/examples/sql/books/books.pro b/examples/sql/books/books.pro index 870e4a6c00..953945912e 100644 --- a/examples/sql/books/books.pro +++ b/examples/sql/books/books.pro @@ -4,7 +4,6 @@ INCLUDEPATH += . HEADERS = bookdelegate.h bookwindow.h initdb.h RESOURCES = books.qrc SOURCES = bookdelegate.cpp main.cpp bookwindow.cpp -FORMS = bookwindow.ui QT += sql widgets widgets requires(qtConfig(tableview)) diff --git a/examples/sql/books/books.qrc b/examples/sql/books/books.qrc index 342638ecb0..1a4dac32cc 100644 --- a/examples/sql/books/books.qrc +++ b/examples/sql/books/books.qrc @@ -1,5 +1,6 @@ <!DOCTYPE RCC><RCC version="1.0"> <qresource prefix="/"> - <file>images/star.png</file> + <file>images/star.svg</file> + <file>images/star-filled.svg</file> </qresource> </RCC> diff --git a/examples/sql/books/bookwindow.cpp b/examples/sql/books/bookwindow.cpp index 2ec5459e1b..6de2d5e80a 100644 --- a/examples/sql/books/bookwindow.cpp +++ b/examples/sql/books/bookwindow.cpp @@ -5,18 +5,27 @@ #include "bookdelegate.h" #include "initdb.h" -#include <QtSql> +#include <QApplication> +#include <QComboBox> +#include <QDataWidgetMapper> +#include <QGridLayout> +#include <QHeaderView> +#include <QLabel> +#include <QLineEdit> +#include <QMenu> +#include <QMenuBar> +#include <QMessageBox> +#include <QPainter> +#include <QScrollBar> +#include <QSpinBox> +#include <QSqlDatabase> +#include <QTableView> BookWindow::BookWindow() { - ui.setupUi(this); - if (!QSqlDatabase::drivers().contains("QSQLITE")) - QMessageBox::critical( - this, - "Unable to load database", - "This demo needs the SQLITE driver" - ); + QMessageBox::critical(this, tr("Unable to load database"), + tr("This demo needs the SQLITE driver")); // Initialize the database: QSqlError err = initDb(); @@ -25,20 +34,87 @@ BookWindow::BookWindow() return; } - // Create the data model: - model = new QSqlRelationalTableModel(ui.bookTable); + // create the central widget for the window + window = new QWidget(this); + setCentralWidget(window); + + createLayout(); + + createModel(); + + // Populate the model + if (!model->select()) { + showError(model->lastError()); + return; + } + + configureWidgets(); + + // create the mappings between the UI elements and the SQL model + createMappings(); + + tableView->setCurrentIndex(model->index(0, 0)); + tableView->selectRow(0); + + createMenuBar(); +} + +void BookWindow::showError(const QSqlError &err) +{ + QMessageBox::critical(this, tr("Unable to initialize Database"), + tr("Error initializing database: %1").arg(err.text())); +} + +void BookWindow::createLayout() +{ + tableView = new QTableView(window); + + gridLayout = new QGridLayout(window); + + titleLabel = new QLabel(tr("Title:"), window); + titleLineEdit = new QLineEdit(window); + authorLabel = new QLabel(tr("Author:"), window); + authorComboBox = new QComboBox(window); + genreLabel = new QLabel(tr("Genre:"), window); + genreComboBox = new QComboBox(window); + yearLabel = new QLabel(tr("Year:"), window); + yearSpinBox = new QSpinBox(window); + ratingLabel = new QLabel(tr("Rating:"), window); + ratingComboBox = new QComboBox(window); + + gridLayout->addWidget(titleLabel, 0, 0, Qt::AlignRight); + gridLayout->addWidget(titleLineEdit, 0, 1, 1, 3); + gridLayout->addWidget(authorLabel, 1, 0, Qt::AlignRight); + gridLayout->addWidget(authorComboBox, 1, 1); + gridLayout->addWidget(yearLabel, 1, 2, Qt::AlignRight); + gridLayout->addWidget(yearSpinBox, 1, 3); + gridLayout->addWidget(genreLabel, 2, 0, Qt::AlignRight); + gridLayout->addWidget(genreComboBox, 2, 1); + gridLayout->addWidget(ratingLabel, 2, 2, Qt::AlignRight); + gridLayout->addWidget(ratingComboBox, 2, 3); + gridLayout->addWidget(tableView, 3, 0, 1, 4, Qt::AlignCenter); + gridLayout->setColumnStretch(1, 1000); + gridLayout->setColumnStretch(3, 1000); + + gridLayout->setContentsMargins(18, 18, 18, 18); + gridLayout->setSpacing(18); + gridLayout->setAlignment(Qt::AlignHCenter); +} + +void BookWindow::createModel() +{ + model = new QSqlRelationalTableModel(tableView); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->setTable("books"); - // Remember the indexes of the columns: authorIdx = model->fieldIndex("author"); genreIdx = model->fieldIndex("genre"); - // Set the relations to the other database tables: + // Set the relations to the other database tables model->setRelation(authorIdx, QSqlRelation("authors", "id", "name")); model->setRelation(genreIdx, QSqlRelation("genres", "id", "name")); - // Set the localized header captions: + // Set the localised header captions model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name")); model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre")); model->setHeaderData(model->fieldIndex("title"), @@ -46,56 +122,81 @@ BookWindow::BookWindow() model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year")); model->setHeaderData(model->fieldIndex("rating"), Qt::Horizontal, tr("Rating")); +} - // Populate the model: - if (!model->select()) { - showError(model->lastError()); - return; +void BookWindow::configureWidgets() +{ + tableView->setModel(model); + tableView->setItemDelegate(new BookDelegate(tableView)); + tableView->setColumnHidden(model->fieldIndex("id"), true); + tableView->verticalHeader()->setVisible(false); + tableView->setSelectionMode(QAbstractItemView::ExtendedSelection); + tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + + // Lock and prohibit resizing of the width of the columns + tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + tableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setFixedHeight(tableView->rowHeight(0)); + + // increment by two to consider the frame + tableView->setFixedWidth(tableView->horizontalHeader()->length() + + tableView->verticalScrollBar()->sizeHint().width() + 2); + tableView->setMaximumHeight(tableView->verticalHeader()->length() + + tableView->horizontalHeader()->height() + 2); + + authorComboBox->setModel(model->relationModel(authorIdx)); + authorComboBox->setModelColumn(model->relationModel(authorIdx)->fieldIndex("name")); + + genreComboBox->setModel(model->relationModel(genreIdx)); + genreComboBox->setModelColumn(model->relationModel(genreIdx)->fieldIndex("name")); + + yearSpinBox->setMaximum(9999); + + const int width = 16; + const int height = width; + const int y = 2; + const int padding = 2; + + QSize iconSize = QSize(width * 5 + padding * 2, width + padding * 2); + QIcon starIcon(QStringLiteral(":images/star.svg")); + QIcon starFilledIcon(QStringLiteral(":images/star-filled.svg")); + + for (int row = 0; row < 6; ++row) { + QPixmap icon(iconSize); + icon.fill(Qt::transparent); + QPainter painter(&icon); + int x = 2; + + for (int col = 0; col < 5; ++col) { + if (col < row) { + starFilledIcon.paint(&painter, QRect(x, y, width, height)); + } else { + starIcon.paint(&painter, QRect(x, y, width, height)); + } + x += width; + } + ratingComboBox->addItem(icon, ""); + ratingComboBox->setItemData(row, QString::number(row + 1)); } - // Set the model and hide the ID column: - ui.bookTable->setModel(model); - ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable)); - ui.bookTable->setColumnHidden(model->fieldIndex("id"), true); - ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection); - - // Initialize the Author combo box: - ui.authorEdit->setModel(model->relationModel(authorIdx)); - ui.authorEdit->setModelColumn( - model->relationModel(authorIdx)->fieldIndex("name")); - - ui.genreEdit->setModel(model->relationModel(genreIdx)); - ui.genreEdit->setModelColumn( - model->relationModel(genreIdx)->fieldIndex("name")); - - // Lock and prohibit resizing of the width of the rating column: - ui.bookTable->horizontalHeader()->setSectionResizeMode( - model->fieldIndex("rating"), - QHeaderView::ResizeToContents); + ratingComboBox->setIconSize(iconSize); +} +void BookWindow::createMappings() +{ QDataWidgetMapper *mapper = new QDataWidgetMapper(this); mapper->setModel(model); mapper->setItemDelegate(new BookDelegate(this)); - mapper->addMapping(ui.titleEdit, model->fieldIndex("title")); - mapper->addMapping(ui.yearEdit, model->fieldIndex("year")); - mapper->addMapping(ui.authorEdit, authorIdx); - mapper->addMapping(ui.genreEdit, genreIdx); - mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating")); - - connect(ui.bookTable->selectionModel(), + mapper->addMapping(titleLineEdit, model->fieldIndex("title")); + mapper->addMapping(yearSpinBox, model->fieldIndex("year")); + mapper->addMapping(authorComboBox, authorIdx); + mapper->addMapping(genreComboBox, genreIdx); + mapper->addMapping(ratingComboBox, model->fieldIndex("rating"), "currentIndex"); + connect(tableView->selectionModel(), &QItemSelectionModel::currentRowChanged, mapper, &QDataWidgetMapper::setCurrentModelIndex ); - - ui.bookTable->setCurrentIndex(model->index(0, 0)); - createMenuBar(); -} - -void BookWindow::showError(const QSqlError &err) -{ - QMessageBox::critical(this, "Unable to initialize Database", - "Error initializing database: " + err.text()); } void BookWindow::createMenuBar() diff --git a/examples/sql/books/bookwindow.h b/examples/sql/books/bookwindow.h index ba569292a6..46d3570df1 100644 --- a/examples/sql/books/bookwindow.h +++ b/examples/sql/books/bookwindow.h @@ -4,11 +4,15 @@ #ifndef BOOKWINDOW_H #define BOOKWINDOW_H -#include <QtWidgets> -#include <QtSql> - -#include "ui_bookwindow.h" - +#include <QMainWindow> +QT_FORWARD_DECLARE_CLASS(QComboBox) +QT_FORWARD_DECLARE_CLASS(QGridLayout) +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QLineEdit) +QT_FORWARD_DECLARE_CLASS(QSpinBox) +QT_FORWARD_DECLARE_CLASS(QSqlError) +QT_FORWARD_DECLARE_CLASS(QSqlRelationalTableModel) +QT_FORWARD_DECLARE_CLASS(QTableView) class BookWindow: public QMainWindow { @@ -21,11 +25,29 @@ private slots: private: void showError(const QSqlError &err); - Ui::BookWindow ui; - QSqlRelationalTableModel *model; - int authorIdx, genreIdx; + QSqlRelationalTableModel *model = nullptr; + int authorIdx = 0, genreIdx = 0; + void createLayout(); + void createModel(); + void configureWidgets(); + void createMappings(); void createMenuBar(); + + QWidget *window = nullptr; + + QGridLayout *gridLayout = nullptr; + QTableView *tableView = nullptr; + QLabel *titleLabel = nullptr; + QLineEdit *titleLineEdit = nullptr; + QLabel *authorLabel = nullptr; + QComboBox *authorComboBox = nullptr; + QLabel *genreLabel = nullptr; + QComboBox *genreComboBox = nullptr; + QLabel *yearLabel = nullptr; + QSpinBox *yearSpinBox = nullptr; + QLabel *ratingLabel = nullptr; + QComboBox *ratingComboBox = nullptr; }; #endif diff --git a/examples/sql/books/bookwindow.ui b/examples/sql/books/bookwindow.ui deleted file mode 100644 index ce8f9f933a..0000000000 --- a/examples/sql/books/bookwindow.ui +++ /dev/null @@ -1,164 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<ui version="4.0"> - <class>BookWindow</class> - <widget class="QMainWindow" name="BookWindow"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>601</width> - <height>420</height> - </rect> - </property> - <property name="windowTitle"> - <string>Books</string> - </property> - <widget class="QWidget" name="centralWidget"> - <layout class="QVBoxLayout"> - <property name="spacing"> - <number>6</number> - </property> - <property name="leftMargin"> - <number>9</number> - </property> - <property name="topMargin"> - <number>9</number> - </property> - <property name="rightMargin"> - <number>9</number> - </property> - <property name="bottomMargin"> - <number>9</number> - </property> - <item> - <widget class="QGroupBox" name="groupBox"> - <property name="title"> - <string/> - </property> - <layout class="QVBoxLayout"> - <property name="spacing"> - <number>6</number> - </property> - <property name="leftMargin"> - <number>9</number> - </property> - <property name="topMargin"> - <number>9</number> - </property> - <property name="rightMargin"> - <number>9</number> - </property> - <property name="bottomMargin"> - <number>9</number> - </property> - <item> - <widget class="QTableView" name="bookTable"> - <property name="selectionBehavior"> - <enum>QAbstractItemView::SelectRows</enum> - </property> - </widget> - </item> - <item> - <widget class="QGroupBox" name="groupBox_2"> - <property name="title"> - <string>Details</string> - </property> - <layout class="QFormLayout"> - <item row="0" column="0"> - <widget class="QLabel" name="label_5"> - <property name="text"> - <string><b>Title:</b></string> - </property> - </widget> - </item> - <item row="0" column="1"> - <widget class="QLineEdit" name="titleEdit"> - <property name="enabled"> - <bool>true</bool> - </property> - </widget> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="label_2"> - <property name="text"> - <string><b>Author: </b></string> - </property> - </widget> - </item> - <item row="1" column="1"> - <widget class="QComboBox" name="authorEdit"> - <property name="enabled"> - <bool>true</bool> - </property> - </widget> - </item> - <item row="2" column="0"> - <widget class="QLabel" name="label_3"> - <property name="text"> - <string><b>Genre:</b></string> - </property> - </widget> - </item> - <item row="2" column="1"> - <widget class="QComboBox" name="genreEdit"> - <property name="enabled"> - <bool>true</bool> - </property> - </widget> - </item> - <item row="3" column="0"> - <widget class="QLabel" name="label_4"> - <property name="text"> - <string><b>Year:</b></string> - </property> - </widget> - </item> - <item row="3" column="1"> - <widget class="QSpinBox" name="yearEdit"> - <property name="enabled"> - <bool>true</bool> - </property> - <property name="prefix"> - <string/> - </property> - <property name="minimum"> - <number>-1000</number> - </property> - <property name="maximum"> - <number>2100</number> - </property> - </widget> - </item> - <item row="4" column="0"> - <widget class="QLabel" name="label"> - <property name="text"> - <string><b>Rating:</b></string> - </property> - </widget> - </item> - <item row="4" column="1"> - <widget class="QSpinBox" name="ratingEdit"> - <property name="maximum"> - <number>5</number> - </property> - </widget> - </item> - </layout> - </widget> - </item> - </layout> - </widget> - </item> - </layout> - </widget> - </widget> - <tabstops> - <tabstop>bookTable</tabstop> - <tabstop>titleEdit</tabstop> - <tabstop>authorEdit</tabstop> - <tabstop>genreEdit</tabstop> - <tabstop>yearEdit</tabstop> - </tabstops> - <resources/> - <connections/> -</ui> diff --git a/examples/sql/books/images/star-filled.svg b/examples/sql/books/images/star-filled.svg new file mode 100644 index 0000000000..8a2aee27fb --- /dev/null +++ b/examples/sql/books/images/star-filled.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="#0d0d0d"><path d="M8.41 18.138L12 15.845l3.59 2.323-.94-4.345 3.162-2.897-4.159-.392L12 6.43l-1.652 4.073-4.159.392 3.162 2.927-.94 4.315zm-1.346 3.696a1.04 1.04 0 0 1-1.567-1.104l1.318-6.033-4.476-4.11c-.665-.611-.293-1.726.604-1.808l5.866-.539 2.229-5.587c.348-.872 1.575-.872 1.923 0l2.229 5.587 5.866.539c.897.082 1.269 1.197.604 1.808l-4.476 4.11 1.318 6.033a1.04 1.04 0 0 1-1.567 1.104L12 18.681l-4.935 3.153z"/><path d="M12 5l-1.796 5.528H4.392l4.702 3.416-1.796 5.528L12 16.056l4.702 3.416-1.796-5.528 4.702-3.416h-5.812L12 5z"/></svg> diff --git a/examples/sql/books/images/star.png b/examples/sql/books/images/star.png Binary files differdeleted file mode 100644 index 87f4464bd5..0000000000 --- a/examples/sql/books/images/star.png +++ /dev/null diff --git a/examples/sql/books/images/star.svg b/examples/sql/books/images/star.svg new file mode 100644 index 0000000000..d959abc182 --- /dev/null +++ b/examples/sql/books/images/star.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none"><path d="M8.41 18.138L12 15.845l3.59 2.323-.94-4.345 3.162-2.897-4.159-.392L12 6.43l-1.652 4.073-4.159.392 3.162 2.927-.94 4.315zm-1.346 3.696a1.04 1.04 0 0 1-1.567-1.104l1.318-6.033-4.476-4.11c-.665-.611-.293-1.726.604-1.808l5.866-.539 2.229-5.587c.348-.872 1.575-.872 1.923 0l2.229 5.587 5.866.539c.897.082 1.269 1.197.604 1.808l-4.476 4.11 1.318 6.033a1.04 1.04 0 0 1-1.567 1.104L12 18.681l-4.935 3.153z" fill="#0d0d0d"/></svg> diff --git a/examples/sql/books/initdb.h b/examples/sql/books/initdb.h index 38fc9aeb71..9de8845a2f 100644 --- a/examples/sql/books/initdb.h +++ b/examples/sql/books/initdb.h @@ -4,7 +4,9 @@ #ifndef INITDB_H #define INITDB_H -#include <QtSql> +#include <QDate> +#include <QSqlError> +#include <QSqlQuery> void addBook(QSqlQuery &q, const QString &title, int year, const QVariant &authorId, const QVariant &genreId, int rating) diff --git a/examples/sql/books/main.cpp b/examples/sql/books/main.cpp index d06568ed36..76a05f1c39 100644 --- a/examples/sql/books/main.cpp +++ b/examples/sql/books/main.cpp @@ -3,12 +3,10 @@ #include "bookwindow.h" -#include <QtWidgets> +#include <QApplication> int main(int argc, char * argv[]) { - Q_INIT_RESOURCE(books); - QApplication app(argc, argv); BookWindow win; diff --git a/examples/sql/cachedtable/CMakeLists.txt b/examples/sql/cachedtable/CMakeLists.txt index 4a19000fa7..af6843b734 100644 --- a/examples/sql/cachedtable/CMakeLists.txt +++ b/examples/sql/cachedtable/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(cachedtable LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/cachedtable") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -33,7 +27,14 @@ target_link_libraries(cachedtable PRIVATE ) install(TARGETS cachedtable - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET cachedtable + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/cachedtable/tableeditor.cpp b/examples/sql/cachedtable/tableeditor.cpp index 97b3fa0d96..b92e256438 100644 --- a/examples/sql/cachedtable/tableeditor.cpp +++ b/examples/sql/cachedtable/tableeditor.cpp @@ -1,11 +1,16 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -#include <QtWidgets> -#include <QtSql> - #include "tableeditor.h" +#include <QDialogButtonBox> +#include <QHBoxLayout> +#include <QMessageBox> +#include <QPushButton> +#include <QSqlError> +#include <QSqlTableModel> +#include <QTableView> + //! [0] TableEditor::TableEditor(const QString &tableName, QWidget *parent) : QWidget(parent) diff --git a/examples/sql/cachedtable/tableeditor.h b/examples/sql/cachedtable/tableeditor.h index dfa50a8934..8c3c56b397 100644 --- a/examples/sql/cachedtable/tableeditor.h +++ b/examples/sql/cachedtable/tableeditor.h @@ -6,11 +6,9 @@ #include <QDialog> -QT_BEGIN_NAMESPACE -class QDialogButtonBox; -class QPushButton; -class QSqlTableModel; -QT_END_NAMESPACE +QT_FORWARD_DECLARE_CLASS(QDialogButtonBox) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QSqlTableModel) //! [0] class TableEditor : public QWidget diff --git a/examples/sql/doc/images/books-demo.png b/examples/sql/doc/images/books-demo.png Binary files differindex 77b3b308c9..29f5c84473 100644 --- a/examples/sql/doc/images/books-demo.png +++ b/examples/sql/doc/images/books-demo.png diff --git a/examples/sql/doc/images/drilldown-example.png b/examples/sql/doc/images/drilldown-example.png Binary files differindex 39a4117637..b6cf443e7c 100644 --- a/examples/sql/doc/images/drilldown-example.png +++ b/examples/sql/doc/images/drilldown-example.png diff --git a/examples/sql/doc/src/books.qdoc b/examples/sql/doc/src/books.qdoc index c08d2f975a..b4ca8bdd2e 100644 --- a/examples/sql/doc/src/books.qdoc +++ b/examples/sql/doc/src/books.qdoc @@ -5,6 +5,7 @@ \example books \title Books \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief Shows how to use Qt SQL classes with a model/view framework. The Books example shows how Qt's SQL classes can be used with the model/view diff --git a/examples/sql/doc/src/cachedtable.qdoc b/examples/sql/doc/src/cachedtable.qdoc index 35b8fdd440..ff60f7b1b7 100644 --- a/examples/sql/doc/src/cachedtable.qdoc +++ b/examples/sql/doc/src/cachedtable.qdoc @@ -3,8 +3,9 @@ /*! \example cachedtable - \title Cached Table Example + \title Cached SQL Table \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The Cached Table example shows how a table view can be used to access a database, caching any changes to the data until the user explicitly submits them using a diff --git a/examples/sql/doc/src/drilldown.qdoc b/examples/sql/doc/src/drilldown.qdoc index 4e432b7016..d334018b4a 100644 --- a/examples/sql/doc/src/drilldown.qdoc +++ b/examples/sql/doc/src/drilldown.qdoc @@ -5,6 +5,7 @@ \example drilldown \title Drill Down Example \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The Drill Down example shows how to read data from a database as well as submit changes, using the QSqlRelationalTableModel and @@ -45,8 +46,8 @@ \snippet drilldown/informationwindow.h 0 When we create an information window, we pass the associated - item ID, a parent, and a pointer to the database, to the - constructor. We will use the database pointer to populate our + item ID, a pointer to the model, and a parent to the + constructor. We will use the model pointer to populate our window with data, while passing the parent parameter on to the base class. The ID is stored for future reference. @@ -153,10 +154,6 @@ We need to use lambdas for connecting the \c enableButtons slot because its signature does not match \c QTextEdit::textChanged and \c QComboBox::currentIndexChanged. - Since the latter has another overload with the signature - \c {const QString &} and the selected signal would be ambiguous, - we need to use \c QOverload<int>::of to select a specific overload - for \c currentIndexChanged. We add all the widgets into a layout, store the item ID and the name of the displayed image file for future reference, and set diff --git a/examples/sql/doc/src/masterdetail.qdoc b/examples/sql/doc/src/masterdetail.qdoc index 9fcf50870b..fec579a6a0 100644 --- a/examples/sql/doc/src/masterdetail.qdoc +++ b/examples/sql/doc/src/masterdetail.qdoc @@ -5,6 +5,7 @@ \example masterdetail \title Master Detail Example \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The Master Detail Example shows how to present data from different data sources in the same application. The album titles, and the diff --git a/examples/sql/doc/src/querymodel.qdoc b/examples/sql/doc/src/querymodel.qdoc index 38f7acab5c..c9fa4cec96 100644 --- a/examples/sql/doc/src/querymodel.qdoc +++ b/examples/sql/doc/src/querymodel.qdoc @@ -5,6 +5,7 @@ \example querymodel \title Query Model Example \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The Query Model example shows how to make customized versions of data obtained from a SQL query, using a model that encapsulates diff --git a/examples/sql/doc/src/relationaltablemodel.qdoc b/examples/sql/doc/src/relationaltablemodel.qdoc index cf95cb4aad..371fef8133 100644 --- a/examples/sql/doc/src/relationaltablemodel.qdoc +++ b/examples/sql/doc/src/relationaltablemodel.qdoc @@ -5,6 +5,7 @@ \example relationaltablemodel \title Relational Table Model Example \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The Relational Table Model example shows how to use table views with a relational model to visualize the relations between items in a database. diff --git a/examples/sql/doc/src/sqlbrowser.qdoc b/examples/sql/doc/src/sqlbrowser.qdoc index 0cabea09aa..ad783f5760 100644 --- a/examples/sql/doc/src/sqlbrowser.qdoc +++ b/examples/sql/doc/src/sqlbrowser.qdoc @@ -5,6 +5,7 @@ \example sqlbrowser \title SQL Browser \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The SQL Browser example shows how a data browser can be used to visualize the results of SQL statements on a live database. diff --git a/examples/sql/doc/src/sqlwidgetmapper.qdoc b/examples/sql/doc/src/sqlwidgetmapper.qdoc index 2e921f479c..0764e601c3 100644 --- a/examples/sql/doc/src/sqlwidgetmapper.qdoc +++ b/examples/sql/doc/src/sqlwidgetmapper.qdoc @@ -5,6 +5,7 @@ \example sqlwidgetmapper \title SQL Widget Mapper Example \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The SQL Widget Mapper example shows how to use a map information from a database to widgets on a form. @@ -101,8 +102,7 @@ As a result, the user is able to select an item from the combo box, and the associated value is written back to the model. - The rest of the constructor is very similar to that of the - \l{Simple Widget Mapper Example}: + The rest of the constructor sets up connections and layouts: \snippet sqlwidgetmapper/window.cpp Set up connections and layouts @@ -115,7 +115,7 @@ \section1 Delegate Class Definition and Implementation The delegate we use to mediate interaction between the widget mapper and - the input widgets is a small QItemDelegate subclass: + the input widgets is a small QStyledItemDelegate subclass: \snippet sqlwidgetmapper/delegate.h Delegate class definition @@ -126,7 +126,7 @@ Since we only provide an empty implementation of the constructor, we concentrate on the other two functions. - The \l{QItemDelegate::}{setEditorData()} implementation takes the data + The \l{QStyledItemDelegate::}{setEditorData()} implementation takes the data referred to by the model index supplied and processes it according to the presence of a \c currentIndex property in the editor widget: @@ -138,10 +138,10 @@ values needed for the \c currentIndex property. As a result, instead of showing "0", "1" or "2" in the combo box, one of - its predefined set of items is shown. We call QItemDelegate::setEditorData() + its predefined set of items is shown. We call QStyledItemDelegate::setEditorData() for widgets without the \c currentIndex property. - The \l{QItemDelegate::}{setModelData()} implementation performs the reverse + The \l{QStyledItemDelegate::}{setModelData()} implementation performs the reverse process, taking the value stored in the widget's \c currentIndex property and storing it back in the model: diff --git a/examples/sql/doc/src/tablemodel.qdoc b/examples/sql/doc/src/tablemodel.qdoc index 420c3cd943..1542d121aa 100644 --- a/examples/sql/doc/src/tablemodel.qdoc +++ b/examples/sql/doc/src/tablemodel.qdoc @@ -5,6 +5,7 @@ \example tablemodel \title Table Model Example \ingroup sql_examples + \examplecategory {Data Processing & I/O} \brief The Table Model example shows how to use a specialized SQL table model with table views to edit information in a database. diff --git a/examples/sql/drilldown/CMakeLists.txt b/examples/sql/drilldown/CMakeLists.txt index 19140080a2..fb9b441fa3 100644 --- a/examples/sql/drilldown/CMakeLists.txt +++ b/examples/sql/drilldown/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(drilldown LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/drilldown") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -50,7 +44,14 @@ qt_add_resources(drilldown "drilldown" ) install(TARGETS drilldown - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET drilldown + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/drilldown/imageitem.cpp b/examples/sql/drilldown/imageitem.cpp index 59f1255f9f..4dfb5ee6e8 100644 --- a/examples/sql/drilldown/imageitem.cpp +++ b/examples/sql/drilldown/imageitem.cpp @@ -54,7 +54,7 @@ void ImageItem::setFrame(int frame) QPointF center = boundingRect().center(); setTransform(QTransform::fromTranslate(center.x(), center.y()), true); - setTransform(QTransform::fromScale(1 + frame / 330.0, 1 + frame / 330.0), true); + setTransform(QTransform::fromScale(1 + frame / 300.0, 1 + frame / 300.0), true); setTransform(QTransform::fromTranslate(-center.x(), -center.y()), true); } //! [3] @@ -62,8 +62,8 @@ void ImageItem::setFrame(int frame) //! [4] void ImageItem::adjust() { - setTransform(QTransform::fromScale(120 / boundingRect().width(), - 120 / boundingRect().height())); + setTransform(QTransform::fromScale(120.0 / boundingRect().width(), + 120.0 / boundingRect().height())); } //! [4] diff --git a/examples/sql/drilldown/imageitem.h b/examples/sql/drilldown/imageitem.h index f6be4d50ab..23a41aa2f2 100644 --- a/examples/sql/drilldown/imageitem.h +++ b/examples/sql/drilldown/imageitem.h @@ -11,7 +11,6 @@ class ImageItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT - public: enum { Type = UserType + 1 }; @@ -25,7 +24,7 @@ protected: void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; -private slots: +private Q_SLOTS: void setFrame(int frame); void updateItemPosition(); diff --git a/examples/sql/drilldown/images/qt-creator.png b/examples/sql/drilldown/images/qt-creator.png Binary files differindex 0602bdcad1..576f9f39ff 100644 --- a/examples/sql/drilldown/images/qt-creator.png +++ b/examples/sql/drilldown/images/qt-creator.png diff --git a/examples/sql/drilldown/images/qt-logo.png b/examples/sql/drilldown/images/qt-logo.png Binary files differindex 7603fa0c90..fb8b1686bd 100644 --- a/examples/sql/drilldown/images/qt-logo.png +++ b/examples/sql/drilldown/images/qt-logo.png diff --git a/examples/sql/drilldown/images/qt-project.png b/examples/sql/drilldown/images/qt-project.png Binary files differindex e066fbe3f9..8c20e3f0c2 100644 --- a/examples/sql/drilldown/images/qt-project.png +++ b/examples/sql/drilldown/images/qt-project.png diff --git a/examples/sql/drilldown/images/qt-quick.png b/examples/sql/drilldown/images/qt-quick.png Binary files differindex 90d9fd075d..a905f47c35 100644 --- a/examples/sql/drilldown/images/qt-quick.png +++ b/examples/sql/drilldown/images/qt-quick.png diff --git a/examples/sql/drilldown/informationwindow.cpp b/examples/sql/drilldown/informationwindow.cpp index 4f9896d74d..d69c91d0cb 100644 --- a/examples/sql/drilldown/informationwindow.cpp +++ b/examples/sql/drilldown/informationwindow.cpp @@ -9,9 +9,9 @@ InformationWindow::InformationWindow(int id, QSqlRelationalTableModel *items, : QDialog(parent) { //! [0] //! [1] - QLabel *itemLabel = new QLabel(tr("Item: ")); - QLabel *descriptionLabel = new QLabel(tr("Description: ")); - QLabel *imageFileLabel = new QLabel(tr("Image file: ")); + QLabel *itemLabel = new QLabel(tr("Item:")); + QLabel *descriptionLabel = new QLabel(tr("Description:")); + QLabel *imageFileLabel = new QLabel(tr("Image file:")); createButtons(); @@ -37,12 +37,8 @@ InformationWindow::InformationWindow(int id, QSqlRelationalTableModel *items, //! [3] //! [4] - connect(descriptionEditor, &QTextEdit::textChanged, [=]() { - enableButtons(); - }); - connect(imageFileEditor, &QComboBox::currentIndexChanged, [=]() { - enableButtons(); - }); + connect(descriptionEditor, &QTextEdit::textChanged, this, [this]() { enableButtons(true); }); + connect(imageFileEditor, &QComboBox::currentIndexChanged, this, [this]() { enableButtons(true); }); QFormLayout *formLayout = new QFormLayout; formLayout->addRow(itemLabel, itemText); diff --git a/examples/sql/drilldown/informationwindow.h b/examples/sql/drilldown/informationwindow.h index 368d99c303..2380463785 100644 --- a/examples/sql/drilldown/informationwindow.h +++ b/examples/sql/drilldown/informationwindow.h @@ -11,22 +11,20 @@ class InformationWindow : public QDialog { Q_OBJECT - public: InformationWindow(int id, QSqlRelationalTableModel *items, QWidget *parent = nullptr); - int id() const; -signals: +Q_SIGNALS: void imageChanged(int id, const QString &fileName); //! [0] //! [1] -private slots: +private Q_SLOTS: void revert(); void submit(); - void enableButtons(bool enable = true); + void enableButtons(bool enable); //! [1] //! [2] diff --git a/examples/sql/drilldown/main.cpp b/examples/sql/drilldown/main.cpp index 5828a37aab..77b8725281 100644 --- a/examples/sql/drilldown/main.cpp +++ b/examples/sql/drilldown/main.cpp @@ -11,8 +11,6 @@ int main(int argc, char *argv[]) { - Q_INIT_RESOURCE(drilldown); - QApplication app(argc, argv); if (!createConnection()) diff --git a/examples/sql/drilldown/view.cpp b/examples/sql/drilldown/view.cpp index f41d32f282..c2f7301a21 100644 --- a/examples/sql/drilldown/view.cpp +++ b/examples/sql/drilldown/view.cpp @@ -87,8 +87,8 @@ void View::showInformation(ImageItem *image) if (!window) { window = new InformationWindow(id, itemTable, this); - connect(window, QOverload<int,const QString &>::of(&InformationWindow::imageChanged), - this, QOverload<int,const QString &>::of(&View::updateImage)); + connect(window, &InformationWindow::imageChanged, + this, &View::updateImage); window->move(pos() + QPoint(20, 40)); window->show(); diff --git a/examples/sql/drilldown/view.h b/examples/sql/drilldown/view.h index acbfeb1558..f44dedce99 100644 --- a/examples/sql/drilldown/view.h +++ b/examples/sql/drilldown/view.h @@ -14,7 +14,6 @@ class InformationWindow; class View : public QGraphicsView { Q_OBJECT - public: View(const QString &items, const QString &images, QWidget *parent = nullptr); @@ -23,7 +22,7 @@ protected: //! [0] //! [1] -private slots: +private Q_SLOTS: void updateImage(int id, const QString &fileName); //! [1] diff --git a/examples/sql/masterdetail/CMakeLists.txt b/examples/sql/masterdetail/CMakeLists.txt index 7a77e6ffb7..558bf70ee2 100644 --- a/examples/sql/masterdetail/CMakeLists.txt +++ b/examples/sql/masterdetail/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(masterdetail LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/masterdetail") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets Xml) qt_standard_project_setup() @@ -48,7 +42,14 @@ qt_add_resources(masterdetail "masterdetail" ) install(TARGETS masterdetail - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET masterdetail + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/masterdetail/dialog.cpp b/examples/sql/masterdetail/dialog.cpp index 19e941af30..0b8ed8a75b 100644 --- a/examples/sql/masterdetail/dialog.cpp +++ b/examples/sql/masterdetail/dialog.cpp @@ -3,10 +3,23 @@ #include "dialog.h" -int uniqueAlbumId; -int uniqueArtistId; - -Dialog::Dialog(QSqlRelationalTableModel *albums, QDomDocument details, +#include <QDialogButtonBox> +#include <QDate> +#include <QDomDocument> +#include <QGroupBox> +#include <QLabel> +#include <QLineEdit> +#include <QMessageBox> +#include <QPushButton> +#include <QSpinBox> +#include <QSqlField> +#include <QSqlRelationalTableModel> +#include <QSqlRecord> +#include <QVBoxLayout> + +int Dialog::s_artistId = 0; +int Dialog::s_albumId = 0; +Dialog::Dialog(QSqlRelationalTableModel *albums, const QDomDocument &details, QFile *output, QWidget *parent) : QDialog(parent) { @@ -25,6 +38,12 @@ Dialog::Dialog(QSqlRelationalTableModel *albums, QDomDocument details, setWindowTitle(tr("Add Album")); } +void Dialog::setInitialAlbumAndArtistId(int albumId, int artistId) +{ + s_albumId = albumId; + s_artistId = artistId; +} + void Dialog::submit() { QString artist = artistEditor->text(); @@ -145,7 +164,7 @@ void Dialog::addTracks(int albumId, const QStringList &tracks) */ } -void Dialog::increaseAlbumCount(QModelIndex artistIndex) +void Dialog::increaseAlbumCount(const QModelIndex &artistIndex) { QSqlTableModel *artistModel = model->relationModel(2); @@ -219,7 +238,7 @@ QDialogButtonBox *Dialog::createButtons() return buttonBox; } -QModelIndex Dialog::indexOfArtist(const QString &artist) +QModelIndex Dialog::indexOfArtist(const QString &artist) const { QSqlTableModel *artistModel = model->relationModel(2); @@ -234,12 +253,12 @@ QModelIndex Dialog::indexOfArtist(const QString &artist) int Dialog::generateArtistId() { - uniqueArtistId += 1; - return uniqueArtistId; + s_artistId += 1; + return s_artistId; } int Dialog::generateAlbumId() { - uniqueAlbumId += 1; - return uniqueAlbumId; + s_albumId += 1; + return s_albumId; } diff --git a/examples/sql/masterdetail/dialog.h b/examples/sql/masterdetail/dialog.h index 0c5a728ebb..2a4f5a0b8e 100644 --- a/examples/sql/masterdetail/dialog.h +++ b/examples/sql/masterdetail/dialog.h @@ -4,17 +4,25 @@ #ifndef DIALOG_H #define DIALOG_H -#include <QtWidgets> -#include <QtSql> -#include <QtXml> +#include <QDialog> +#include <QDomDocument> + +QT_FORWARD_DECLARE_CLASS(QDialogButtonBox) +QT_FORWARD_DECLARE_CLASS(QFile) +QT_FORWARD_DECLARE_CLASS(QGroupBox) +QT_FORWARD_DECLARE_CLASS(QLineEdit) +QT_FORWARD_DECLARE_CLASS(QModelIndex) +QT_FORWARD_DECLARE_CLASS(QSpinBox) +QT_FORWARD_DECLARE_CLASS(QSqlRelationalTableModel) class Dialog : public QDialog { Q_OBJECT public: - Dialog(QSqlRelationalTableModel *albums, QDomDocument details, + Dialog(QSqlRelationalTableModel *albums, const QDomDocument &details, QFile *output, QWidget *parent = nullptr); + static void setInitialAlbumAndArtistId(int albumId, int artistId); private slots: void revert(); @@ -27,10 +35,8 @@ private: QDialogButtonBox *createButtons(); QGroupBox *createInputWidgets(); int findArtistId(const QString &artist); - static int generateAlbumId(); - static int generateArtistId(); - void increaseAlbumCount(QModelIndex artistIndex); - QModelIndex indexOfArtist(const QString &artist); + void increaseAlbumCount(const QModelIndex &artistIndex); + QModelIndex indexOfArtist(const QString &artist) const; QSqlRelationalTableModel *model; QDomDocument albumDetails; @@ -40,6 +46,11 @@ private: QLineEdit *titleEditor; QSpinBox *yearEditor; QLineEdit *tracksEditor; + + static int generateAlbumId(); + static int generateArtistId(); + static int s_artistId; + static int s_albumId; }; #endif diff --git a/examples/sql/masterdetail/main.cpp b/examples/sql/masterdetail/main.cpp index 8b6ee61828..50d99cf24e 100644 --- a/examples/sql/masterdetail/main.cpp +++ b/examples/sql/masterdetail/main.cpp @@ -7,12 +7,8 @@ #include <QApplication> #include <QFile> -#include <stdlib.h> - int main(int argc, char *argv[]) { - Q_INIT_RESOURCE(masterdetail); - QApplication app(argc, argv); if (!createConnection()) diff --git a/examples/sql/masterdetail/mainwindow.cpp b/examples/sql/masterdetail/mainwindow.cpp index d720db1033..020a149b22 100644 --- a/examples/sql/masterdetail/mainwindow.cpp +++ b/examples/sql/masterdetail/mainwindow.cpp @@ -4,12 +4,20 @@ #include "mainwindow.h" #include "dialog.h" -#include <QtWidgets> -#include <QtSql> -#include <QtXml> - -extern int uniqueAlbumId; -extern int uniqueArtistId; +#include <QApplication> +#include <QComboBox> +#include <QHeaderView> +#include <QFile> +#include <QGridLayout> +#include <QGroupBox> +#include <QLabel> +#include <QListWidget> +#include <QMenu> +#include <QMenuBar> +#include <QMessageBox> +#include <QSqlRecord> +#include <QSqlRelationalTableModel> +#include <QTableView> MainWindow::MainWindow(const QString &artistTable, const QString &albumTable, QFile *albumDetails, QWidget *parent) @@ -28,13 +36,12 @@ MainWindow::MainWindow(const QString &artistTable, const QString &albumTable, QGroupBox *details = createDetailsGroupBox(); artistView->setCurrentIndex(0); - uniqueAlbumId = model->rowCount(); - uniqueArtistId = artistView->count(); + Dialog::setInitialAlbumAndArtistId(model->rowCount(), artistView->count()); connect(model, &QSqlRelationalTableModel::rowsInserted, - this, &MainWindow::updateHeader); + this, &MainWindow::adjustHeader); connect(model, &QSqlRelationalTableModel::rowsRemoved, - this, &MainWindow::updateHeader); + this, &MainWindow::adjustHeader); QGridLayout *layout = new QGridLayout; layout->addWidget(artists, 0, 0); @@ -67,7 +74,7 @@ void MainWindow::changeArtist(int row) } } -void MainWindow::showArtistProfile(QModelIndex index) +void MainWindow::showArtistProfile(const QModelIndex &index) { QSqlRecord record = model->relationModel(2)->record(index.row()); @@ -84,7 +91,7 @@ void MainWindow::showArtistProfile(QModelIndex index) imageLabel->hide(); } -void MainWindow::showAlbumDetails(QModelIndex index) +void MainWindow::showAlbumDetails(const QModelIndex &index) { QSqlRecord record = model->record(index.row()); @@ -113,14 +120,11 @@ void MainWindow::getTrackList(QDomNode album) { trackList->clear(); - QDomNodeList tracks = album.childNodes(); - QDomNode track; - QString trackNumber; - + const QDomNodeList tracks = album.childNodes(); for (int i = 0; i < tracks.count(); ++i) { - track = tracks.item(i); - trackNumber = track.toElement().attribute("number"); + const QDomNode track = tracks.item(i); + const QString trackNumber = track.toElement().attribute("number"); QListWidgetItem *item = new QListWidgetItem(trackList); item->setText(trackNumber + ": " + track.toElement().text()); @@ -132,7 +136,7 @@ void MainWindow::addAlbum() Dialog *dialog = new Dialog(model, albumData, file, this); int accepted = dialog->exec(); - if (accepted == 1) { + if (accepted == QDialog::Accepted) { int lastRow = model->rowCount() - 1; albumView->selectRow(lastRow); albumView->scrollToBottom(); @@ -142,10 +146,10 @@ void MainWindow::addAlbum() void MainWindow::deleteAlbum() { - QModelIndexList selection = albumView->selectionModel()->selectedRows(0); + const QModelIndexList selection = albumView->selectionModel()->selectedRows(0); if (!selection.empty()) { - QModelIndex idIndex = selection.at(0); + const QModelIndex &idIndex = selection.at(0); int id = idIndex.data().toInt(); QString title = idIndex.sibling(idIndex.row(), 1).data().toString(); QString artist = idIndex.sibling(idIndex.row(), 2).data().toString(); @@ -172,9 +176,7 @@ void MainWindow::deleteAlbum() void MainWindow::removeAlbumFromFile(int id) { - QDomNodeList albums = albumData.elementsByTagName("album"); - for (int i = 0; i < albums.count(); ++i) { QDomNode node = albums.item(i); if (node.toElement().attribute("id").toInt() == id) { @@ -197,12 +199,12 @@ void MainWindow::removeAlbumFromFile(int id) */ } -void MainWindow::removeAlbumFromDatabase(QModelIndex index) +void MainWindow::removeAlbumFromDatabase(const QModelIndex &index) { model->removeRow(index.row()); } -void MainWindow::decreaseAlbumCount(QModelIndex artistIndex) +void MainWindow::decreaseAlbumCount(const QModelIndex &artistIndex) { int row = artistIndex.row(); QModelIndex albumCountIndex = artistIndex.sibling(row, 2); @@ -358,7 +360,7 @@ void MainWindow::showImageLabel() imageLabel->show(); } -QModelIndex MainWindow::indexOfArtist(const QString &artist) +QModelIndex MainWindow::indexOfArtist(const QString &artist) const { QSqlTableModel *artistModel = model->relationModel(2); @@ -370,11 +372,6 @@ QModelIndex MainWindow::indexOfArtist(const QString &artist) return QModelIndex(); } -void MainWindow::updateHeader(QModelIndex, int, int) -{ - adjustHeader(); -} - void MainWindow::adjustHeader() { albumView->hideColumn(0); diff --git a/examples/sql/masterdetail/mainwindow.h b/examples/sql/masterdetail/mainwindow.h index a5f9e70648..cc2a5c9f59 100644 --- a/examples/sql/masterdetail/mainwindow.h +++ b/examples/sql/masterdetail/mainwindow.h @@ -8,15 +8,13 @@ #include <QMainWindow> #include <QModelIndex> -QT_BEGIN_NAMESPACE -class QComboBox; -class QFile; -class QGroupBox; -class QLabel; -class QListWidget; -class QSqlRelationalTableModel; -class QTableView; -QT_END_NAMESPACE +QT_FORWARD_DECLARE_CLASS(QComboBox) +QT_FORWARD_DECLARE_CLASS(QFile) +QT_FORWARD_DECLARE_CLASS(QGroupBox) +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QListWidget) +QT_FORWARD_DECLARE_CLASS(QSqlRelationalTableModel) +QT_FORWARD_DECLARE_CLASS(QTableView) class MainWindow : public QMainWindow { @@ -31,21 +29,20 @@ private slots: void addAlbum(); void changeArtist(int row); void deleteAlbum(); - void showAlbumDetails(QModelIndex index); - void showArtistProfile(QModelIndex index); - void updateHeader(QModelIndex, int, int); + void showAlbumDetails(const QModelIndex &index); + void showArtistProfile(const QModelIndex &index); + void adjustHeader(); private: - void adjustHeader(); QGroupBox *createAlbumGroupBox(); QGroupBox *createArtistGroupBox(); QGroupBox *createDetailsGroupBox(); void createMenuBar(); - void decreaseAlbumCount(QModelIndex artistIndex); + void decreaseAlbumCount(const QModelIndex &artistIndex); void getTrackList(QDomNode album); - QModelIndex indexOfArtist(const QString &artist); + QModelIndex indexOfArtist(const QString &artist) const; void readAlbumData(); - void removeAlbumFromDatabase(QModelIndex album); + void removeAlbumFromDatabase(const QModelIndex &album); void removeAlbumFromFile(int id); void showImageLabel(); diff --git a/examples/sql/querymodel/CMakeLists.txt b/examples/sql/querymodel/CMakeLists.txt index d6720c0f67..b7d863ab05 100644 --- a/examples/sql/querymodel/CMakeLists.txt +++ b/examples/sql/querymodel/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(querymodel LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/querymodel") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -34,7 +28,14 @@ target_link_libraries(querymodel PRIVATE ) install(TARGETS querymodel - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET querymodel + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/querymodel/customsqlmodel.cpp b/examples/sql/querymodel/customsqlmodel.cpp index 9063911218..e87be12f09 100644 --- a/examples/sql/querymodel/customsqlmodel.cpp +++ b/examples/sql/querymodel/customsqlmodel.cpp @@ -1,10 +1,10 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -#include <QtWidgets> - #include "customsqlmodel.h" +#include <QColor> + CustomSqlModel::CustomSqlModel(QObject *parent) : QSqlQueryModel(parent) { diff --git a/examples/sql/querymodel/editablesqlmodel.cpp b/examples/sql/querymodel/editablesqlmodel.cpp index b7cb930020..dc91666c06 100644 --- a/examples/sql/querymodel/editablesqlmodel.cpp +++ b/examples/sql/querymodel/editablesqlmodel.cpp @@ -1,18 +1,17 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -#include <QtSql> - #include "editablesqlmodel.h" +#include <QSqlQuery> + EditableSqlModel::EditableSqlModel(QObject *parent) : QSqlQueryModel(parent) { } //! [0] -Qt::ItemFlags EditableSqlModel::flags( - const QModelIndex &index) const +Qt::ItemFlags EditableSqlModel::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QSqlQueryModel::flags(index); if (index.column() == 1 || index.column() == 2) @@ -33,11 +32,10 @@ bool EditableSqlModel::setData(const QModelIndex &index, const QVariant &value, clear(); bool ok; - if (index.column() == 1) { + if (index.column() == 1) ok = setFirstName(id, value.toString()); - } else { + else ok = setLastName(id, value.toString()); - } refresh(); return ok; } diff --git a/examples/sql/querymodel/main.cpp b/examples/sql/querymodel/main.cpp index 8c5af768e3..a4680f7fe8 100644 --- a/examples/sql/querymodel/main.cpp +++ b/examples/sql/querymodel/main.cpp @@ -8,8 +8,6 @@ #include <QApplication> #include <QTableView> -#include <stdlib.h> - void initializeModel(QSqlQueryModel *model) { model->setQuery("select * from person"); diff --git a/examples/sql/relationaltablemodel/CMakeLists.txt b/examples/sql/relationaltablemodel/CMakeLists.txt index cd19b75e07..fcca1f182b 100644 --- a/examples/sql/relationaltablemodel/CMakeLists.txt +++ b/examples/sql/relationaltablemodel/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(relationaltablemodel LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/relationaltablemodel") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -32,7 +26,14 @@ target_link_libraries(relationaltablemodel PRIVATE ) install(TARGETS relationaltablemodel - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET relationaltablemodel + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/sqlbrowser/CMakeLists.txt b/examples/sql/sqlbrowser/CMakeLists.txt index 210a53125b..a124ae203c 100644 --- a/examples/sql/sqlbrowser/CMakeLists.txt +++ b/examples/sql/sqlbrowser/CMakeLists.txt @@ -1,17 +1,11 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(sqlbrowser LANGUAGES CXX) set(CMAKE_INCLUDE_CURRENT_DIR ON) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/sqlbrowser") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -37,7 +31,14 @@ target_link_libraries(sqlbrowser PRIVATE ) install(TARGETS sqlbrowser - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET sqlbrowser + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/sqlbrowser/browser.cpp b/examples/sql/sqlbrowser/browser.cpp index 98270fd5b5..9a99999702 100644 --- a/examples/sql/sqlbrowser/browser.cpp +++ b/examples/sql/sqlbrowser/browser.cpp @@ -3,23 +3,49 @@ #include "browser.h" #include "qsqlconnectiondialog.h" - -#include <QtWidgets> -#include <QtSql> +#include <ui_browserwidget.h> + +#include <QAction> +#include <QMessageBox> +#include <QStandardItemModel> +#include <QSqlDriver> +#include <QSqlError> +#include <QSqlField> +#include <QSqlQuery> +#include <QSqlRecord> +#include <QTextEdit> +#include <QTimer> Browser::Browser(QWidget *parent) : QWidget(parent) + , m_ui(new Ui::Browser) { - setupUi(this); - - table->addAction(insertRowAction); - table->addAction(deleteRowAction); - table->addAction(fieldStrategyAction); - table->addAction(rowStrategyAction); - table->addAction(manualStrategyAction); - table->addAction(submitAction); - table->addAction(revertAction); - table->addAction(selectAction); + m_ui->setupUi(this); + + m_ui->table->addAction(m_ui->insertRowAction); + m_ui->table->addAction(m_ui->deleteRowAction); + m_ui->table->addAction(m_ui->fieldStrategyAction); + m_ui->table->addAction(m_ui->rowStrategyAction); + m_ui->table->addAction(m_ui->manualStrategyAction); + m_ui->table->addAction(m_ui->submitAction); + m_ui->table->addAction(m_ui->revertAction); + m_ui->table->addAction(m_ui->selectAction); + + connect(m_ui->insertRowAction, &QAction::triggered, this, &Browser::insertRow); + connect(m_ui->deleteRowAction, &QAction::triggered, this, &Browser::deleteRow); + connect(m_ui->fieldStrategyAction, &QAction::triggered, this, &Browser::onFieldStrategyAction); + connect(m_ui->rowStrategyAction, &QAction::triggered, this, &Browser::onRowStrategyAction); + connect(m_ui->sqlEdit, &QTextEdit::textChanged, this, &Browser::updateActions); + + connect(m_ui->connectionWidget, &ConnectionWidget::tableActivated, + this, &Browser::showTable); + connect(m_ui->connectionWidget, &ConnectionWidget::metaDataRequested, + this, &Browser::showMetaData); + + connect(m_ui->submitButton, &QPushButton::clicked, + this, &Browser::onSubmitButton); + connect(m_ui->clearButton, &QPushButton::clicked, + this, &Browser::onClearButton); if (QSqlDatabase::drivers().isEmpty()) QMessageBox::information(this, tr("No database drivers found"), @@ -27,18 +53,22 @@ Browser::Browser(QWidget *parent) "Please check the documentation how to build the " "Qt SQL plugins.")); - emit statusMessage(tr("Ready.")); + QTimer::singleShot(0, this, [this]() { + updateActions(); + emit statusMessage(tr("Ready.")); + }); } Browser::~Browser() { + delete m_ui; } void Browser::exec() { - QSqlQueryModel *model = new QSqlQueryModel(table); - model->setQuery(QSqlQuery(sqlEdit->toPlainText(), connectionWidget->currentDatabase())); - table->setModel(model); + QSqlQueryModel *model = new QSqlQueryModel(m_ui->table); + model->setQuery(QSqlQuery(m_ui->sqlEdit->toPlainText(), m_ui->connectionWidget->currentDatabase())); + m_ui->table->setModel(model); if (model->lastError().type() != QSqlError::NoError) emit statusMessage(model->lastError().text()); @@ -52,7 +82,7 @@ void Browser::exec() } QSqlError Browser::addConnection(const QString &driver, const QString &dbName, const QString &host, - const QString &user, const QString &passwd, int port) + const QString &user, const QString &passwd, int port) { static int cCount = 0; @@ -66,12 +96,12 @@ QSqlError Browser::addConnection(const QString &driver, const QString &dbName, c db = QSqlDatabase(); QSqlDatabase::removeDatabase(QString("Browser%1").arg(cCount)); } - connectionWidget->refresh(); + m_ui->connectionWidget->refresh(); return err; } -void Browser::addConnection() +void Browser::openNewConnectionDialog() { QSqlConnectionDialog dialog(this); if (dialog.exec() != QDialog::Accepted) @@ -82,10 +112,14 @@ void Browser::addConnection() QSqlDatabase::removeDatabase("in_mem_db"); QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "in_mem_db"); db.setDatabaseName(":memory:"); - if (!db.open()) - QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " - "opening the connection: ") + db.lastError().text()); - QSqlQuery q("", db); + if (!db.open()) { + QMessageBox::warning(this, tr("Unable to open database"), + tr("An error occurred while " + "opening the connection: %1") .arg(db.lastError().text())); + return; + } + db.transaction(); + QSqlQuery q(db); q.exec("drop table Movies"); q.exec("drop table Names"); q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)"); @@ -100,37 +134,43 @@ void Browser::addConnection() q.exec("insert into Names values (2, 'Donald', 'Duck', 'Andeby')"); q.exec("insert into Names values (3, 'Buck', 'Rogers', 'Paris')"); q.exec("insert into Names values (4, 'Sherlock', 'Holmes', 'London')"); - connectionWidget->refresh(); + db.commit(); + m_ui->connectionWidget->refresh(); } else { QSqlError err = addConnection(dialog.driverName(), dialog.databaseName(), dialog.hostName(), - dialog.userName(), dialog.password(), dialog.port()); + dialog.userName(), dialog.password(), dialog.port()); if (err.type() != QSqlError::NoError) - QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " - "opening the connection: ") + err.text()); + QMessageBox::warning(this, tr("Unable to open database"), + tr("An error occurred while " + "opening the connection: %1").arg(err.text())); } } void Browser::showTable(const QString &t) { - QSqlTableModel *model = new CustomModel(table, connectionWidget->currentDatabase()); + QSqlTableModel *model = new CustomModel(m_ui->table, m_ui->connectionWidget->currentDatabase()); model->setEditStrategy(QSqlTableModel::OnRowChange); - model->setTable(connectionWidget->currentDatabase().driver()->escapeIdentifier(t, QSqlDriver::TableName)); + model->setTable(m_ui->connectionWidget->currentDatabase().driver()->escapeIdentifier(t, QSqlDriver::TableName)); model->select(); if (model->lastError().type() != QSqlError::NoError) emit statusMessage(model->lastError().text()); - table->setModel(model); - table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed); - connect(table->selectionModel(), &QItemSelectionModel::currentRowChanged, - this, &Browser::currentChanged); + m_ui->table->setModel(model); + m_ui->table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed); + connect(m_ui->table->selectionModel(), &QItemSelectionModel::currentRowChanged, + this, &Browser::updateActions); + + connect(m_ui->submitAction, &QAction::triggered, model, &QSqlTableModel::submitAll); + connect(m_ui->revertAction, &QAction::triggered, model, &QSqlTableModel::revertAll); + connect(m_ui->selectAction, &QAction::triggered, model, &QSqlTableModel::select); updateActions(); } void Browser::showMetaData(const QString &t) { - QSqlRecord rec = connectionWidget->currentDatabase().record(t); - QStandardItemModel *model = new QStandardItemModel(table); + QSqlRecord rec = m_ui->connectionWidget->currentDatabase().record(t); + QStandardItemModel *model = new QStandardItemModel(m_ui->table); model->insertRows(0, rec.count()); model->insertColumns(0, 7); @@ -146,9 +186,7 @@ void Browser::showMetaData(const QString &t) for (int i = 0; i < rec.count(); ++i) { QSqlField fld = rec.field(i); model->setData(model->index(i, 0), fld.name()); - model->setData(model->index(i, 1), fld.typeID() == -1 - ? QString(fld.metaType().name()) - : QString("%1 (%2)").arg(fld.metaType().name()).arg(fld.typeID())); + model->setData(model->index(i, 1), QString::fromUtf8(fld.metaType().name())); model->setData(model->index(i, 2), fld.length()); model->setData(model->index(i, 3), fld.precision()); model->setData(model->index(i, 4), fld.requiredStatus() == -1 ? QVariant("?") @@ -157,37 +195,37 @@ void Browser::showMetaData(const QString &t) model->setData(model->index(i, 6), fld.defaultValue()); } - table->setModel(model); - table->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_ui->table->setModel(model); + m_ui->table->setEditTriggers(QAbstractItemView::NoEditTriggers); updateActions(); } void Browser::insertRow() { - QSqlTableModel *model = qobject_cast<QSqlTableModel *>(table->model()); + QSqlTableModel *model = qobject_cast<QSqlTableModel *>(m_ui->table->model()); if (!model) return; - QModelIndex insertIndex = table->currentIndex(); + QModelIndex insertIndex = m_ui->table->currentIndex(); int row = insertIndex.row() == -1 ? 0 : insertIndex.row(); model->insertRow(row); insertIndex = model->index(row, 0); - table->setCurrentIndex(insertIndex); - table->edit(insertIndex); + m_ui->table->setCurrentIndex(insertIndex); + m_ui->table->edit(insertIndex); } void Browser::deleteRow() { - QSqlTableModel *model = qobject_cast<QSqlTableModel *>(table->model()); + QSqlTableModel *model = qobject_cast<QSqlTableModel *>(m_ui->table->model()); if (!model) return; - QModelIndexList currentSelection = table->selectionModel()->selectedIndexes(); - for (int i = 0; i < currentSelection.count(); ++i) { - if (currentSelection.at(i).column() != 0) + const QModelIndexList currentSelection = m_ui->table->selectionModel()->selectedIndexes(); + for (const auto &idx : currentSelection) { + if (idx.column() != 0) continue; - model->removeRow(currentSelection.at(i).row()); + model->removeRow(idx.row()); } updateActions(); @@ -195,74 +233,70 @@ void Browser::deleteRow() void Browser::updateActions() { - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); - bool enableIns = tm; - bool enableDel = enableIns && table->currentIndex().isValid(); + QSqlTableModel *tm = qobject_cast<QSqlTableModel *>(m_ui->table->model()); + bool enableIns = tm != nullptr; + bool enableDel = enableIns && m_ui->table->currentIndex().isValid(); - insertRowAction->setEnabled(enableIns); - deleteRowAction->setEnabled(enableDel); + m_ui->insertRowAction->setEnabled(enableIns); + m_ui->deleteRowAction->setEnabled(enableDel); - fieldStrategyAction->setEnabled(tm); - rowStrategyAction->setEnabled(tm); - manualStrategyAction->setEnabled(tm); - submitAction->setEnabled(tm); - revertAction->setEnabled(tm); - selectAction->setEnabled(tm); + m_ui->submitAction->setEnabled(tm); + m_ui->revertAction->setEnabled(tm); + m_ui->selectAction->setEnabled(tm); + + const bool isEmpty = m_ui->sqlEdit->toPlainText().isEmpty(); + m_ui->submitButton->setEnabled(m_ui->connectionWidget->currentDatabase().isOpen() && !isEmpty); + m_ui->clearButton->setEnabled(!isEmpty); if (tm) { QSqlTableModel::EditStrategy es = tm->editStrategy(); - fieldStrategyAction->setChecked(es == QSqlTableModel::OnFieldChange); - rowStrategyAction->setChecked(es == QSqlTableModel::OnRowChange); - manualStrategyAction->setChecked(es == QSqlTableModel::OnManualSubmit); + m_ui->fieldStrategyAction->setChecked(es == QSqlTableModel::OnFieldChange); + m_ui->rowStrategyAction->setChecked(es == QSqlTableModel::OnRowChange); + m_ui->manualStrategyAction->setChecked(es == QSqlTableModel::OnManualSubmit); + } else { + m_ui->fieldStrategyAction->setEnabled(false); + m_ui->rowStrategyAction->setEnabled(false); + m_ui->manualStrategyAction->setEnabled(false); } } void Browser::about() { - QMessageBox::about(this, tr("About"), tr("The SQL Browser demonstration " - "shows how a data browser can be used to visualize the results of SQL" - "statements on a live database")); + QMessageBox::about(this, tr("About"), + tr("The SQL Browser demonstration shows how a data browser " + "can be used to visualize the results of SQL " + "statements on a live database")); } -void Browser::on_fieldStrategyAction_triggered() +void Browser::onFieldStrategyAction() { - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); + QSqlTableModel *tm = qobject_cast<QSqlTableModel *>(m_ui->table->model()); if (tm) tm->setEditStrategy(QSqlTableModel::OnFieldChange); } -void Browser::on_rowStrategyAction_triggered() +void Browser::onRowStrategyAction() { - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); + QSqlTableModel *tm = qobject_cast<QSqlTableModel *>(m_ui->table->model()); if (tm) tm->setEditStrategy(QSqlTableModel::OnRowChange); } -void Browser::on_manualStrategyAction_triggered() +void Browser::onManualStrategyAction() { - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); + QSqlTableModel *tm = qobject_cast<QSqlTableModel *>(m_ui->table->model()); if (tm) tm->setEditStrategy(QSqlTableModel::OnManualSubmit); } -void Browser::on_submitAction_triggered() -{ - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); - if (tm) - tm->submitAll(); -} - -void Browser::on_revertAction_triggered() +void Browser::onSubmitButton() { - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); - if (tm) - tm->revertAll(); + exec(); + m_ui->sqlEdit->setFocus(); } -void Browser::on_selectAction_triggered() +void Browser::onClearButton() { - QSqlTableModel * tm = qobject_cast<QSqlTableModel *>(table->model()); - if (tm) - tm->select(); + m_ui->sqlEdit->clear(); + m_ui->sqlEdit->setFocus(); } - diff --git a/examples/sql/sqlbrowser/browser.h b/examples/sql/sqlbrowser/browser.h index cf959703b3..c61048c84a 100644 --- a/examples/sql/sqlbrowser/browser.h +++ b/examples/sql/sqlbrowser/browser.h @@ -6,72 +6,58 @@ #include <QWidget> #include <QSqlTableModel> -#include "ui_browserwidget.h" -class ConnectionWidget; -QT_FORWARD_DECLARE_CLASS(QTableView) -QT_FORWARD_DECLARE_CLASS(QPushButton) -QT_FORWARD_DECLARE_CLASS(QTextEdit) QT_FORWARD_DECLARE_CLASS(QSqlError) -class Browser: public QWidget, private Ui::Browser +QT_BEGIN_NAMESPACE +namespace Ui +{ +class Browser; +} +QT_END_NAMESPACE + +class Browser : public QWidget { Q_OBJECT public: Browser(QWidget *parent = nullptr); - virtual ~Browser(); + ~Browser(); QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host, - const QString &user, const QString &passwd, int port = -1); + const QString &user, const QString &passwd, int port); +public slots: + void openNewConnectionDialog(); + void about(); + +protected: void insertRow(); void deleteRow(); void updateActions(); -public slots: +protected slots: void exec(); void showTable(const QString &table); void showMetaData(const QString &table); - void addConnection(); - void currentChanged() { updateActions(); } - void about(); - void on_insertRowAction_triggered() - { insertRow(); } - void on_deleteRowAction_triggered() - { deleteRow(); } - void on_fieldStrategyAction_triggered(); - void on_rowStrategyAction_triggered(); - void on_manualStrategyAction_triggered(); - void on_submitAction_triggered(); - void on_revertAction_triggered(); - void on_selectAction_triggered(); - void on_connectionWidget_tableActivated(const QString &table) - { showTable(table); } - void on_connectionWidget_metaDataRequested(const QString &table) - { showMetaData(table); } - void on_submitButton_clicked() - { - exec(); - sqlEdit->setFocus(); - } - void on_clearButton_clicked() - { - sqlEdit->clear(); - sqlEdit->setFocus(); - } + void onFieldStrategyAction(); + void onRowStrategyAction(); + void onManualStrategyAction(); + void onSubmitButton(); + void onClearButton(); signals: void statusMessage(const QString &message); + +private: + Ui::Browser *m_ui; }; -class CustomModel: public QSqlTableModel +class CustomModel : public QSqlTableModel { Q_OBJECT public: - explicit CustomModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase()) - : QSqlTableModel(parent, db) {} - + using QSqlTableModel::QSqlTableModel; QVariant data(const QModelIndex &idx, int role) const override { if (role == Qt::BackgroundRole && isDirty(idx)) diff --git a/examples/sql/sqlbrowser/connectionwidget.cpp b/examples/sql/sqlbrowser/connectionwidget.cpp index 99ad537994..da6796d7e5 100644 --- a/examples/sql/sqlbrowser/connectionwidget.cpp +++ b/examples/sql/sqlbrowser/connectionwidget.cpp @@ -3,17 +3,19 @@ #include "connectionwidget.h" -#include <QtWidgets> -#include <QtSql> +#include <QAction> +#include <QHeaderView> +#include <QSqlDatabase> +#include <QTreeWidget> +#include <QVBoxLayout> ConnectionWidget::ConnectionWidget(QWidget *parent) : QWidget(parent) + , tree(new QTreeWidget(this)) { QVBoxLayout *layout = new QVBoxLayout(this); - tree = new QTreeWidget(this); - tree->setObjectName(QLatin1String("tree")); - tree->setHeaderLabels(QStringList(tr("database"))); - tree->header()->setSectionResizeMode(QHeaderView::Stretch); + tree->setHeaderLabels(QStringList(tr("Database"))); + tree->header()->setStretchLastSection(true); QAction *refreshAction = new QAction(tr("Refresh"), tree); metaDataAction = new QAction(tr("Show Schema"), tree); connect(refreshAction, &QAction::triggered, this, &ConnectionWidget::refresh); @@ -24,34 +26,37 @@ ConnectionWidget::ConnectionWidget(QWidget *parent) layout->addWidget(tree); - QMetaObject::connectSlotsByName(this); + connect(tree, &QTreeWidget::itemActivated, + this, &ConnectionWidget::onItemActivated); + connect(tree, &QTreeWidget::currentItemChanged, + this, &ConnectionWidget::onCurrentItemChanged); } ConnectionWidget::~ConnectionWidget() { } -static QString qDBCaption(const QSqlDatabase &db) -{ - QString nm = db.driverName(); - nm.append(QLatin1Char(':')); - if (!db.userName().isEmpty()) - nm.append(db.userName()).append(QLatin1Char('@')); - nm.append(db.databaseName()); - return nm; -} void ConnectionWidget::refresh() { + const auto qDBCaption = [](const QSqlDatabase &db) + { + QString nm = db.driverName() + QLatin1Char(':'); + if (!db.userName().isEmpty()) + nm += db.userName() + QLatin1Char('@'); + nm += db.databaseName(); + return nm; + }; + tree->clear(); - QStringList connectionNames = QSqlDatabase::connectionNames(); + const QStringList connectionNames = QSqlDatabase::connectionNames(); bool gotActiveDb = false; - for (int i = 0; i < connectionNames.count(); ++i) { + for (const auto &connectionName : connectionNames) { QTreeWidgetItem *root = new QTreeWidgetItem(tree); - QSqlDatabase db = QSqlDatabase::database(connectionNames.at(i), false); + QSqlDatabase db = QSqlDatabase::database(connectionName, false); root->setText(0, qDBCaption(db)); - if (connectionNames.at(i) == activeDb) { + if (connectionName == activeDb) { gotActiveDb = true; setActive(root); } @@ -76,15 +81,15 @@ QSqlDatabase ConnectionWidget::currentDatabase() const return QSqlDatabase::database(activeDb); } -static void qSetBold(QTreeWidgetItem *item, bool bold) -{ - QFont font = item->font(0); - font.setBold(bold); - item->setFont(0, font); -} - void ConnectionWidget::setActive(QTreeWidgetItem *item) { + const auto qSetBold = [](QTreeWidgetItem *item, bool bold) + { + QFont font = item->font(0); + font.setBold(bold); + item->setFont(0, font); + }; + for (int i = 0; i < tree->topLevelItemCount(); ++i) { if (tree->topLevelItem(i)->font(0).bold()) qSetBold(tree->topLevelItem(i), false); @@ -97,7 +102,7 @@ void ConnectionWidget::setActive(QTreeWidgetItem *item) activeDb = QSqlDatabase::connectionNames().value(tree->indexOfTopLevelItem(item)); } -void ConnectionWidget::on_tree_itemActivated(QTreeWidgetItem *item, int /* column */) +void ConnectionWidget::onItemActivated(QTreeWidgetItem *item) { if (!item) return; @@ -119,7 +124,7 @@ void ConnectionWidget::showMetaData() emit metaDataRequested(cItem->text(0)); } -void ConnectionWidget::on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) +void ConnectionWidget::onCurrentItemChanged(QTreeWidgetItem *current) { metaDataAction->setEnabled(current && current->parent()); } diff --git a/examples/sql/sqlbrowser/connectionwidget.h b/examples/sql/sqlbrowser/connectionwidget.h index a5b1edc7e3..a00296f3c5 100644 --- a/examples/sql/sqlbrowser/connectionwidget.h +++ b/examples/sql/sqlbrowser/connectionwidget.h @@ -9,14 +9,13 @@ QT_FORWARD_DECLARE_CLASS(QTreeWidget) QT_FORWARD_DECLARE_CLASS(QTreeWidgetItem) QT_FORWARD_DECLARE_CLASS(QSqlDatabase) -QT_FORWARD_DECLARE_CLASS(QMenu) -class ConnectionWidget: public QWidget +class ConnectionWidget : public QWidget { Q_OBJECT public: ConnectionWidget(QWidget *parent = nullptr); - virtual ~ConnectionWidget(); + ~ConnectionWidget(); QSqlDatabase currentDatabase() const; @@ -27,8 +26,8 @@ signals: public slots: void refresh(); void showMetaData(); - void on_tree_itemActivated(QTreeWidgetItem *item, int column); - void on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); + void onItemActivated(QTreeWidgetItem *item); + void onCurrentItemChanged(QTreeWidgetItem *current); private: void setActive(QTreeWidgetItem *); diff --git a/examples/sql/sqlbrowser/main.cpp b/examples/sql/sqlbrowser/main.cpp index c6babea96f..b3fa8af142 100644 --- a/examples/sql/sqlbrowser/main.cpp +++ b/examples/sql/sqlbrowser/main.cpp @@ -3,16 +3,21 @@ #include "browser.h" -#include <QtCore> -#include <QtWidgets> -#include <QtSql> +#include <QApplication> +#include <QMainWindow> +#include <QMenu> +#include <QMenuBar> +#include <QSqlError> +#include <QStatusBar> +#include <QUrl> void addConnectionsFromCommandline(const QStringList &args, Browser *browser) { - for (int i = 1; i < args.count(); ++i) { - QUrl url(args.at(i), QUrl::TolerantMode); + for (qsizetype i = 1; i < args.count(); ++i) { + const auto &arg = args.at(i); + const QUrl url(arg, QUrl::TolerantMode); if (!url.isValid()) { - qWarning("Invalid URL: %s", qPrintable(args.at(i))); + qWarning("Invalid URL: %s", qPrintable(arg)); continue; } QSqlError err = browser->addConnection(url.scheme(), url.path().mid(1), url.host(), @@ -27,29 +32,32 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); QMainWindow mainWin; - mainWin.setWindowTitle(QObject::tr("Qt SQL Browser")); + mainWin.setWindowTitle(QApplication::translate("MainWindow", "Qt SQL Browser")); Browser browser(&mainWin); mainWin.setCentralWidget(&browser); QMenu *fileMenu = mainWin.menuBar()->addMenu(QObject::tr("&File")); - fileMenu->addAction(QObject::tr("Add &Connection..."), - [&]() { browser.addConnection(); }); + fileMenu->addAction(QApplication::translate("MainWindow", "Add &Connection..."), + &browser, &Browser::openNewConnectionDialog); fileMenu->addSeparator(); - fileMenu->addAction(QObject::tr("&Quit"), []() { qApp->quit(); }); + fileMenu->addAction(QApplication::translate("MainWindow", "&Quit"), + qApp, &QApplication::quit); QMenu *helpMenu = mainWin.menuBar()->addMenu(QObject::tr("&Help")); - helpMenu->addAction(QObject::tr("About"), [&]() { browser.about(); }); - helpMenu->addAction(QObject::tr("About Qt"), []() { qApp->aboutQt(); }); + helpMenu->addAction(QApplication::translate("MainWindow", "About"), + &browser, &Browser::about); + helpMenu->addAction(QApplication::translate("MainWindow", "About Qt"), + qApp, &QApplication::aboutQt); - QObject::connect(&browser, &Browser::statusMessage, [&mainWin](const QString &text) { - mainWin.statusBar()->showMessage(text); - }); + QObject::connect(&browser, &Browser::statusMessage, + &mainWin, [&mainWin](const QString &text) { mainWin.statusBar()->showMessage(text); }); addConnectionsFromCommandline(app.arguments(), &browser); mainWin.show(); if (QSqlDatabase::connectionNames().isEmpty()) - QMetaObject::invokeMethod(&browser, "addConnection", Qt::QueuedConnection); + QMetaObject::invokeMethod(&browser, &Browser::openNewConnectionDialog, + Qt::QueuedConnection); return app.exec(); } diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp b/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp index e3ab2b9c10..2b85e95805 100644 --- a/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp @@ -2,69 +2,86 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause #include "qsqlconnectiondialog.h" -#include "ui_qsqlconnectiondialog.h" +#include <ui_qsqlconnectiondialog.h> +#include <QCheckBox> +#include <QMessageBox> +#include <QPushButton> #include <QSqlDatabase> QSqlConnectionDialog::QSqlConnectionDialog(QWidget *parent) : QDialog(parent) + , m_ui(new Ui::QSqlConnectionDialogUi) { - ui.setupUi(this); + m_ui->setupUi(this); QStringList drivers = QSqlDatabase::drivers(); if (!drivers.contains("QSQLITE")) - ui.dbCheckBox->setEnabled(false); + m_ui->dbCheckBox->setEnabled(false); - ui.comboDriver->addItems(drivers); + m_ui->comboDriver->addItems(drivers); + + connect(m_ui->okButton, &QPushButton::clicked, + this, &QSqlConnectionDialog::onOkButton); + connect(m_ui->cancelButton, &QPushButton::clicked, + this, &QSqlConnectionDialog::reject); + connect(m_ui->dbCheckBox, &QCheckBox::stateChanged, + this, &QSqlConnectionDialog::onDbCheckBox); } QSqlConnectionDialog::~QSqlConnectionDialog() { + delete m_ui; } QString QSqlConnectionDialog::driverName() const { - return ui.comboDriver->currentText(); + return m_ui->comboDriver->currentText(); } QString QSqlConnectionDialog::databaseName() const { - return ui.editDatabase->text(); + return m_ui->editDatabase->text(); } QString QSqlConnectionDialog::userName() const { - return ui.editUsername->text(); + return m_ui->editUsername->text(); } QString QSqlConnectionDialog::password() const { - return ui.editPassword->text(); + return m_ui->editPassword->text(); } QString QSqlConnectionDialog::hostName() const { - return ui.editHostname->text(); + return m_ui->editHostname->text(); } int QSqlConnectionDialog::port() const { - return ui.portSpinBox->value(); + return m_ui->portSpinBox->value(); } bool QSqlConnectionDialog::useInMemoryDatabase() const { - return ui.dbCheckBox->isChecked(); + return m_ui->dbCheckBox->isChecked(); } -void QSqlConnectionDialog::on_okButton_clicked() +void QSqlConnectionDialog::onOkButton() { - if (ui.comboDriver->currentText().isEmpty()) { + if (m_ui->comboDriver->currentText().isEmpty()) { QMessageBox::information(this, tr("No database driver selected"), tr("Please select a database driver")); - ui.comboDriver->setFocus(); + m_ui->comboDriver->setFocus(); } else { accept(); } } + +void QSqlConnectionDialog::onDbCheckBox() +{ + m_ui->connGroupBox->setEnabled(!m_ui->dbCheckBox->isChecked()); +} diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.h b/examples/sql/sqlbrowser/qsqlconnectiondialog.h index 0f7d9386e2..a6384bb5b7 100644 --- a/examples/sql/sqlbrowser/qsqlconnectiondialog.h +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.h @@ -5,11 +5,15 @@ #define QSQLCONNECTIONDIALOG_H #include <QDialog> -#include <QMessageBox> -#include "ui_qsqlconnectiondialog.h" +QT_BEGIN_NAMESPACE +namespace Ui +{ +class QSqlConnectionDialogUi; +} +QT_END_NAMESPACE -class QSqlConnectionDialog: public QDialog +class QSqlConnectionDialog : public QDialog { Q_OBJECT public: @@ -25,12 +29,11 @@ public: bool useInMemoryDatabase() const; private slots: - void on_okButton_clicked(); - void on_cancelButton_clicked() { reject(); } - void on_dbCheckBox_clicked() { ui.connGroupBox->setEnabled(!ui.dbCheckBox->isChecked()); } + void onOkButton(); + void onDbCheckBox(); private: - Ui::QSqlConnectionDialogUi ui; + Ui::QSqlConnectionDialogUi *m_ui; }; #endif diff --git a/examples/sql/sqlwidgetmapper/CMakeLists.txt b/examples/sql/sqlwidgetmapper/CMakeLists.txt index e0bb4447d4..91ce3cf339 100644 --- a/examples/sql/sqlwidgetmapper/CMakeLists.txt +++ b/examples/sql/sqlwidgetmapper/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(sqlwidgetmapper LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/sqlwidgetmapper") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -32,7 +26,14 @@ target_link_libraries(sqlwidgetmapper PRIVATE ) install(TARGETS sqlwidgetmapper - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET sqlwidgetmapper + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/sqlwidgetmapper/window.cpp b/examples/sql/sqlwidgetmapper/window.cpp index fee3bc78dd..cd44174f84 100644 --- a/examples/sql/sqlwidgetmapper/window.cpp +++ b/examples/sql/sqlwidgetmapper/window.cpp @@ -1,11 +1,20 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause -#include <QtWidgets> -#include <QtSql> - #include "window.h" +#include <QComboBox> +#include <QDataWidgetMapper> +#include <QGridLayout> +#include <QLabel> +#include <QLineEdit> +#include <QMessageBox> +#include <QPushButton> +#include <QSqlQuery> +#include <QSqlRelationalDelegate> +#include <QSqlTableModel> +#include <QTextEdit> + //! [Set up widgets] Window::Window(QWidget *parent) : QWidget(parent) diff --git a/examples/sql/sqlwidgetmapper/window.h b/examples/sql/sqlwidgetmapper/window.h index c3b01155af..9af9628b90 100644 --- a/examples/sql/sqlwidgetmapper/window.h +++ b/examples/sql/sqlwidgetmapper/window.h @@ -6,18 +6,16 @@ #include <QWidget> -QT_BEGIN_NAMESPACE -class QComboBox; -class QDataWidgetMapper; -class QItemSelectionModel; -class QLabel; -class QLineEdit; -class QPushButton; -class QSqlRelationalTableModel; -class QStandardItemModel; -class QStringListModel; -class QTextEdit; -QT_END_NAMESPACE +QT_FORWARD_DECLARE_CLASS(QComboBox) +QT_FORWARD_DECLARE_CLASS(QDataWidgetMapper) +QT_FORWARD_DECLARE_CLASS(QItemSelectionModel) +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QLineEdit) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QSqlRelationalTableModel) +QT_FORWARD_DECLARE_CLASS(QStandardItemModel) +QT_FORWARD_DECLARE_CLASS(QStringListModel) +QT_FORWARD_DECLARE_CLASS(QTextEdit) //! [Window definition] class Window : public QWidget diff --git a/examples/sql/tablemodel/CMakeLists.txt b/examples/sql/tablemodel/CMakeLists.txt index 7b65d81029..28919bb69a 100644 --- a/examples/sql/tablemodel/CMakeLists.txt +++ b/examples/sql/tablemodel/CMakeLists.txt @@ -1,15 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. -# SPDX-License-Identifier: BSD-3-Clause +# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(tablemodel LANGUAGES CXX) -if(NOT DEFINED INSTALL_EXAMPLESDIR) - set(INSTALL_EXAMPLESDIR "examples") -endif() - -set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/sql/tablemodel") - find_package(Qt6 REQUIRED COMPONENTS Core Gui Sql Widgets) qt_standard_project_setup() @@ -32,7 +26,14 @@ target_link_libraries(tablemodel PRIVATE ) install(TARGETS tablemodel - RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}" - BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}" - LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}" + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) + +qt_generate_deploy_app_script( + TARGET tablemodel + OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR ) +install(SCRIPT ${deploy_script}) diff --git a/examples/sql/tablemodel/tablemodel.cpp b/examples/sql/tablemodel/tablemodel.cpp index ae0aa17719..04c114dc63 100644 --- a/examples/sql/tablemodel/tablemodel.cpp +++ b/examples/sql/tablemodel/tablemodel.cpp @@ -6,8 +6,6 @@ #include <QSqlTableModel> #include <QTableView> -#include <stdlib.h> - void initializeModel(QSqlTableModel *model) { model->setTable("person"); |