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,8 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
add_subdirectory(addressbook)
add_subdirectory(widgets)
add_subdirectory(modelview)
add_subdirectory(gettingStarted)
qt_internal_add_example(notepad)

View File

@ -0,0 +1,6 @@
Qt is supplied with tutorials that have been written to provide developers
with an introduction to the Qt API.
Documentation for tutorials can be found in the Tutorials
link in the main documentation.

View File

@ -0,0 +1,10 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
qt_internal_add_example(part1)
qt_internal_add_example(part2)
qt_internal_add_example(part3)
qt_internal_add_example(part4)
qt_internal_add_example(part5)
qt_internal_add_example(part6)
qt_internal_add_example(part7)

View File

@ -0,0 +1,40 @@
The Address Book Tutorial shows how to put together a simple yet
fully-functioning GUI application. The tutorial chapters can be found in the
Qt documentation, which can be viewed using Qt Assistant or a Web browser.
The tutorial is also available online at
http://qt-project.org/doc/qt-5.0/qtwidgets/tutorials-addressbook.html
All programs corresponding to the chapters in the tutorial should
automatically be built when Qt is compiled, or will be provided as
pre-built executables if you have obtained a binary package of Qt.
If you have only compiled the Qt libraries, use the following instructions
to build the tutorial.
On Linux/Unix:
Typing 'make' in this directory builds all the programs (part1/part1,
part2/part2, part3/part3 and so on). Typing 'make' in each subdirectory
builds just that tutorial program.
On Windows:
Create a single Visual Studio project for the tutorial directory in
the usual way. You can do this by typing the following at the command
line:
qmake -tp vc
You should now be able to open the project file in Visual Studio and
build all of the tutorial programs at the same time.
On Mac OS X:
Create an Xcode project with the .pro file in the tutorial directory.
You can do this by typing the following at the command line:
qmake -spec macx-xcode
Then open the generated Xcode project in Xcode and build it.

View File

@ -0,0 +1,6 @@
TEMPLATE = subdirs
SUBDIRS = part1 part2 part3 part4 part5 part6 part7
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook
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(part1 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/addressbook/part1")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(part1
addressbook.cpp addressbook.h
main.cpp
)
set_target_properties(part1 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(part1 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS part1
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,30 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
//! [constructor and input fields]
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
//! [constructor and input fields]
//! [layout]
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
//! [layout]
//![setting the layout]
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
//! [setting the layout]

View File

@ -0,0 +1,29 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QLabel;
class QLineEdit;
class QTextEdit;
QT_END_NAMESPACE
//! [class definition]
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
private:
QLineEdit *nameLine;
QTextEdit *addressText;
};
//! [class definition]
#endif

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 "addressbook.h"
//! [main function]
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
AddressBook addressBook;
addressBook.show();
return app.exec();
}
//! [main function]

View File

@ -0,0 +1,11 @@
QT += widgets
SOURCES = addressbook.cpp \
main.cpp
HEADERS = addressbook.h
QMAKE_PROJECT_NAME = ab_part1
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part1
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(part2 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/addressbook/part2")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(part2
addressbook.cpp addressbook.h
main.cpp
)
set_target_properties(part2 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(part2 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS part2
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,123 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
//! [setting readonly 1]
nameLine->setReadOnly(true);
//! [setting readonly 1]
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
//! [setting readonly 2]
addressText->setReadOnly(true);
//! [setting readonly 2]
//! [pushbutton declaration]
addButton = new QPushButton(tr("&Add"));
addButton->show();
submitButton = new QPushButton(tr("&Submit"));
submitButton->hide();
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->hide();
//! [pushbutton declaration]
//! [connecting signals and slots]
connect(addButton, &QPushButton::clicked,
this, &AddressBook::addContact);
connect(submitButton, &QPushButton::clicked,
this, &AddressBook::submitContact);
connect(cancelButton, &QPushButton::clicked,
this, &AddressBook::cancel);
//! [connecting signals and slots]
//! [vertical layout]
QVBoxLayout *buttonLayout1 = new QVBoxLayout;
buttonLayout1->addWidget(addButton, Qt::AlignTop);
buttonLayout1->addWidget(submitButton);
buttonLayout1->addWidget(cancelButton);
buttonLayout1->addStretch();
//! [vertical layout]
//! [grid layout]
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
mainLayout->addLayout(buttonLayout1, 1, 2);
//! [grid layout]
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
//! [addContact]
void AddressBook::addContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
nameLine->clear();
addressText->clear();
nameLine->setReadOnly(false);
nameLine->setFocus(Qt::OtherFocusReason);
addressText->setReadOnly(false);
addButton->setEnabled(false);
submitButton->show();
cancelButton->show();
}
//! [addContact]
//! [submitContact part1]
void AddressBook::submitContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (name.isEmpty() || address.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name and address."));
return;
}
//! [submitContact part1]
//! [submitContact part2]
if (!contacts.contains(name)) {
contacts.insert(name, address);
QMessageBox::information(this, tr("Add Successful"),
tr("\"%1\" has been added to your address book.").arg(name));
} else {
QMessageBox::information(this, tr("Add Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
return;
}
//! [submitContact part2]
//! [submitContact part3]
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
submitButton->hide();
cancelButton->hide();
}
//! [submitContact part3]
//! [cancel]
void AddressBook::cancel()
{
nameLine->setText(oldName);
nameLine->setReadOnly(true);
addressText->setText(oldAddress);
addressText->setReadOnly(true);
addButton->setEnabled(true);
submitButton->hide();
cancelButton->hide();
}
//! [cancel]

View File

@ -0,0 +1,47 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QMap>
QT_BEGIN_NAMESPACE
class QLabel;
class QLineEdit;
class QPushButton;
class QTextEdit;
QT_END_NAMESPACE
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
//! [slots]
public slots:
void addContact();
void submitContact();
void cancel();
//! [slots]
//! [pushbutton declaration]
private:
QPushButton *addButton;
QPushButton *submitButton;
QPushButton *cancelButton;
QLineEdit *nameLine;
QTextEdit *addressText;
//! [pushbutton declaration]
//! [remaining private variables]
QMap<QString, QString> contacts;
QString oldName;
QString oldAddress;
};
//! [remaining private variables]
#endif

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 "addressbook.h"
//! [main function]
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
AddressBook addressBook;
addressBook.show();
return app.exec();
}
//! [main function]

View File

@ -0,0 +1,11 @@
QT += widgets
SOURCES = addressbook.cpp \
main.cpp
HEADERS = addressbook.h
QMAKE_PROJECT_NAME = ab_part2
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part2
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(part3 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/addressbook/part3")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(part3
addressbook.cpp addressbook.h
main.cpp
)
set_target_properties(part3 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(part3 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS part3
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,182 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
nameLine->setReadOnly(true);
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
addressText->setReadOnly(true);
addButton = new QPushButton(tr("&Add"));
addButton->show();
submitButton = new QPushButton(tr("&Submit"));
submitButton->hide();
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->hide();
//! [navigation pushbuttons]
nextButton = new QPushButton(tr("&Next"));
nextButton->setEnabled(false);
previousButton = new QPushButton(tr("&Previous"));
previousButton->setEnabled(false);
//! [navigation pushbuttons]
connect(addButton, &QPushButton::clicked,
this, &AddressBook::addContact);
connect(submitButton, &QPushButton::clicked,
this, &AddressBook::submitContact);
connect(cancelButton, &QPushButton::clicked,
this, &AddressBook::cancel);
//! [connecting navigation signals]
connect(nextButton, &QPushButton::clicked,
this, &AddressBook::next);
connect(previousButton, &QPushButton::clicked,
this, &AddressBook::previous);
//! [connecting navigation signals]
QVBoxLayout *buttonLayout1 = new QVBoxLayout;
buttonLayout1->addWidget(addButton, Qt::AlignTop);
buttonLayout1->addWidget(submitButton);
buttonLayout1->addWidget(cancelButton);
buttonLayout1->addStretch();
//! [navigation layout]
QHBoxLayout *buttonLayout2 = new QHBoxLayout;
buttonLayout2->addWidget(previousButton);
buttonLayout2->addWidget(nextButton);
//! [ navigation layout]
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
mainLayout->addLayout(buttonLayout1, 1, 2);
//! [adding navigation layout]
mainLayout->addLayout(buttonLayout2, 2, 1);
//! [adding navigation layout]
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
void AddressBook::addContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
nameLine->clear();
addressText->clear();
nameLine->setReadOnly(false);
nameLine->setFocus(Qt::OtherFocusReason);
addressText->setReadOnly(false);
addButton->setEnabled(false);
//! [disabling navigation]
nextButton->setEnabled(false);
previousButton->setEnabled(false);
//! [disabling navigation]
submitButton->show();
cancelButton->show();
}
void AddressBook::submitContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (name.isEmpty() || address.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name and address."));
return;
}
if (!contacts.contains(name)) {
contacts.insert(name, address);
QMessageBox::information(this, tr("Add Successful"),
tr("\"%1\" has been added to your address book.").arg(name));
} else {
QMessageBox::information(this, tr("Add Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
//! [enabling navigation]
int number = contacts.size();
nextButton->setEnabled(number > 1);
previousButton->setEnabled(number > 1);
//! [enabling navigation]
submitButton->hide();
cancelButton->hide();
}
void AddressBook::cancel()
{
nameLine->setText(oldName);
addressText->setText(oldAddress);
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
int number = contacts.size();
nextButton->setEnabled(number > 1);
previousButton->setEnabled(number > 1);
submitButton->hide();
cancelButton->hide();
}
//! [next() function]
void AddressBook::next()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i != contacts.end())
i++;
if (i == contacts.end())
i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
//! [next() function]
//! [previous() function]
void AddressBook::previous()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i == contacts.end()){
nameLine->clear();
addressText->clear();
return;
}
if (i == contacts.begin())
i = contacts.end();
i--;
nameLine->setText(i.key());
addressText->setText(i.value());
}
//! [previous() function]

View File

@ -0,0 +1,49 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QMap>
QT_BEGIN_NAMESPACE
class QLabel;
class QLineEdit;
class QPushButton;
class QTextEdit;
QT_END_NAMESPACE
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
public slots:
void addContact();
void submitContact();
void cancel();
//! [navigation functions]
void next();
void previous();
//! [navigation functions]
private:
QPushButton *addButton;
QPushButton *submitButton;
QPushButton *cancelButton;
//! [navigation pushbuttons]
QPushButton *nextButton;
QPushButton *previousButton;
//! [navigation pushbuttons]
QLineEdit *nameLine;
QTextEdit *addressText;
QMap<QString, QString> contacts;
QString oldName;
QString oldAddress;
};
#endif

View File

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

View File

@ -0,0 +1,11 @@
QT += widgets
SOURCES = addressbook.cpp \
main.cpp
HEADERS = addressbook.h
QMAKE_PROJECT_NAME = ab_part3
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part3
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(part4 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/addressbook/part4")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(part4
addressbook.cpp addressbook.h
main.cpp
)
set_target_properties(part4 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(part4 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS part4
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,258 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
nameLine->setReadOnly(true);
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
addressText->setReadOnly(true);
addButton = new QPushButton(tr("&Add"));
//! [edit and remove buttons]
editButton = new QPushButton(tr("&Edit"));
editButton->setEnabled(false);
removeButton = new QPushButton(tr("&Remove"));
removeButton->setEnabled(false);
//! [edit and remove buttons]
submitButton = new QPushButton(tr("&Submit"));
submitButton->hide();
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->hide();
nextButton = new QPushButton(tr("&Next"));
nextButton->setEnabled(false);
previousButton = new QPushButton(tr("&Previous"));
previousButton->setEnabled(false);
connect(addButton, &QPushButton::clicked,
this, &AddressBook::addContact);
connect(submitButton, &QPushButton::clicked,
this, &AddressBook::submitContact);
//! [connecting edit and remove]
connect(editButton, &QPushButton::clicked,
this, &AddressBook::editContact);
connect(removeButton, &QPushButton::clicked,
this, &AddressBook::removeContact);
//! [connecting edit and remove]
connect(cancelButton, &QPushButton::clicked,
this, &AddressBook::cancel);
connect(nextButton, &QPushButton::clicked,
this, &AddressBook::next);
connect(previousButton, &QPushButton::clicked,
this, &AddressBook::previous);
QVBoxLayout *buttonLayout1 = new QVBoxLayout;
buttonLayout1->addWidget(addButton);
//! [adding edit and remove to the layout]
buttonLayout1->addWidget(editButton);
buttonLayout1->addWidget(removeButton);
//! [adding edit and remove to the layout]
buttonLayout1->addWidget(submitButton);
buttonLayout1->addWidget(cancelButton);
buttonLayout1->addStretch();
QHBoxLayout *buttonLayout2 = new QHBoxLayout;
buttonLayout2->addWidget(previousButton);
buttonLayout2->addWidget(nextButton);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
mainLayout->addLayout(buttonLayout1, 1, 2);
mainLayout->addLayout(buttonLayout2, 2, 1);
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
void AddressBook::addContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
nameLine->clear();
addressText->clear();
updateInterface(AddingMode);
}
//! [editContact() function]
void AddressBook::editContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
updateInterface(EditingMode);
}
//! [editContact() function]
//! [submitContact() function beginning]
void AddressBook::submitContact()
{
//! [submitContact() function beginning]
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (name.isEmpty() || address.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name and address."));
return;
}
//! [submitContact() function part1]
if (currentMode == AddingMode) {
if (!contacts.contains(name)) {
contacts.insert(name, address);
QMessageBox::information(this, tr("Add Successful"),
tr("\"%1\" has been added to your address book.").arg(name));
} else {
QMessageBox::information(this, tr("Add Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
//! [submitContact() function part1]
//! [submitContact() function part2]
} else if (currentMode == EditingMode) {
if (oldName != name) {
if (!contacts.contains(name)) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(oldName));
contacts.remove(oldName);
contacts.insert(name, address);
} else {
QMessageBox::information(this, tr("Edit Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (oldAddress != address) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(name));
contacts[name] = address;
}
}
updateInterface(NavigationMode);
}
//! [submitContact() function part2]
void AddressBook::cancel()
{
nameLine->setText(oldName);
addressText->setText(oldAddress);
updateInterface(NavigationMode);
}
//! [removeContact() function]
void AddressBook::removeContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (contacts.contains(name)) {
int button = QMessageBox::question(this,
tr("Confirm Remove"),
tr("Are you sure you want to remove \"%1\"?").arg(name),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) {
previous();
contacts.remove(name);
QMessageBox::information(this, tr("Remove Successful"),
tr("\"%1\" has been removed from your address book.").arg(name));
}
}
updateInterface(NavigationMode);
}
//! [removeContact() function]
void AddressBook::next()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i != contacts.end())
i++;
if (i == contacts.end())
i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
void AddressBook::previous()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i == contacts.end()) {
nameLine->clear();
addressText->clear();
return;
}
if (i == contacts.begin())
i = contacts.end();
i--;
nameLine->setText(i.key());
addressText->setText(i.value());
}
//! [update interface() part 1]
void AddressBook::updateInterface(Mode mode)
{
currentMode = mode;
switch (currentMode) {
case AddingMode:
case EditingMode:
nameLine->setReadOnly(false);
nameLine->setFocus(Qt::OtherFocusReason);
addressText->setReadOnly(false);
addButton->setEnabled(false);
editButton->setEnabled(false);
removeButton->setEnabled(false);
nextButton->setEnabled(false);
previousButton->setEnabled(false);
submitButton->show();
cancelButton->show();
break;
//! [update interface() part 1]
//! [update interface() part 2]
case NavigationMode:
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
int number = contacts.size();
editButton->setEnabled(number >= 1);
removeButton->setEnabled(number >= 1);
nextButton->setEnabled(number > 1);
previousButton->setEnabled(number >1 );
submitButton->hide();
cancelButton->hide();
break;
}
}
//! [update interface() part 2]

View File

@ -0,0 +1,62 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QMap>
QT_BEGIN_NAMESPACE
class QPushButton;
class QLabel;
class QLineEdit;
class QTextEdit;
QT_END_NAMESPACE
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
//! [Mode enum]
enum Mode { NavigationMode, AddingMode, EditingMode };
//! [Mode enum]
public slots:
void addContact();
void submitContact();
void cancel();
//! [edit and remove slots]
void editContact();
void removeContact();
//! [edit and remove slots]
void next();
void previous();
private:
//! [updateInterface() declaration]
void updateInterface(Mode mode);
//! [updateInterface() declaration]
QPushButton *addButton;
//! [buttons declaration]
QPushButton *editButton;
QPushButton *removeButton;
//! [buttons declaration]
QPushButton *submitButton;
QPushButton *cancelButton;
QPushButton *nextButton;
QPushButton *previousButton;
QLineEdit *nameLine;
QTextEdit *addressText;
QMap<QString, QString> contacts;
QString oldName;
QString oldAddress;
//! [mode declaration]
Mode currentMode;
//! [mode declaration]
};
#endif

View File

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

View File

@ -0,0 +1,11 @@
QT += widgets
SOURCES = addressbook.cpp \
main.cpp
HEADERS = addressbook.h
QMAKE_PROJECT_NAME = ab_part4
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part4
INSTALLS += target

View File

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

View File

@ -0,0 +1,283 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
nameLine->setReadOnly(true);
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
addressText->setReadOnly(true);
addButton = new QPushButton(tr("&Add"));
editButton = new QPushButton(tr("&Edit"));
editButton->setEnabled(false);
removeButton = new QPushButton(tr("&Remove"));
removeButton->setEnabled(false);
//! [instantiating findButton]
findButton = new QPushButton(tr("&Find"));
findButton->setEnabled(false);
//! [instantiating findButton]
submitButton = new QPushButton(tr("&Submit"));
submitButton->hide();
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->hide();
nextButton = new QPushButton(tr("&Next"));
nextButton->setEnabled(false);
previousButton = new QPushButton(tr("&Previous"));
previousButton->setEnabled(false);
//! [instantiating FindDialog]
dialog = new FindDialog(this);
//! [instantiating FindDialog]
connect(addButton, &QPushButton::clicked,
this, &AddressBook::addContact);
connect(submitButton, &QPushButton::clicked,
this, &AddressBook::submitContact);
connect(editButton, &QPushButton::clicked,
this, &AddressBook::editContact);
connect(removeButton, &QPushButton::clicked,
this, &AddressBook::removeContact);
connect(cancelButton, &QPushButton::clicked,
this, &AddressBook::cancel);
//! [signals and slots for find]
connect(findButton, &QPushButton::clicked,
this, &AddressBook::findContact);
//! [signals and slots for find]
connect(nextButton, &QPushButton::clicked,
this, &AddressBook::next);
connect(previousButton, &QPushButton::clicked,
this, &AddressBook::previous);
QVBoxLayout *buttonLayout1 = new QVBoxLayout;
buttonLayout1->addWidget(addButton);
buttonLayout1->addWidget(editButton);
buttonLayout1->addWidget(removeButton);
//! [adding findButton to layout]
buttonLayout1->addWidget(findButton);
//! [adding findButton to layout]
buttonLayout1->addWidget(submitButton);
buttonLayout1->addWidget(cancelButton);
buttonLayout1->addStretch();
QHBoxLayout *buttonLayout2 = new QHBoxLayout;
buttonLayout2->addWidget(previousButton);
buttonLayout2->addWidget(nextButton);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
mainLayout->addLayout(buttonLayout1, 1, 2);
mainLayout->addLayout(buttonLayout2, 2, 1);
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
void AddressBook::addContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
nameLine->clear();
addressText->clear();
updateInterface(AddingMode);
}
void AddressBook::editContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
updateInterface(EditingMode);
}
void AddressBook::submitContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (name.isEmpty() || address.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name and address."));
return;
}
if (currentMode == AddingMode) {
if (!contacts.contains(name)) {
contacts.insert(name, address);
QMessageBox::information(this, tr("Add Successful"),
tr("\"%1\" has been added to your address book.").arg(name));
} else {
QMessageBox::information(this, tr("Add Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (currentMode == EditingMode) {
if (oldName != name) {
if (!contacts.contains(name)) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(oldName));
contacts.remove(oldName);
contacts.insert(name, address);
} else {
QMessageBox::information(this, tr("Edit Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (oldAddress != address) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(name));
contacts[name] = address;
}
}
updateInterface(NavigationMode);
}
void AddressBook::cancel()
{
nameLine->setText(oldName);
addressText->setText(oldAddress);
updateInterface(NavigationMode);
}
void AddressBook::removeContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (contacts.contains(name)) {
int button = QMessageBox::question(this,
tr("Confirm Remove"),
tr("Are you sure you want to remove \"%1\"?").arg(name),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) {
previous();
contacts.remove(name);
QMessageBox::information(this, tr("Remove Successful"),
tr("\"%1\" has been removed from your address book.").arg(name));
}
}
updateInterface(NavigationMode);
}
void AddressBook::next()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i != contacts.end())
i++;
if (i == contacts.end())
i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
void AddressBook::previous()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i == contacts.end()) {
nameLine->clear();
addressText->clear();
return;
}
if (i == contacts.begin())
i = contacts.end();
i--;
nameLine->setText(i.key());
addressText->setText(i.value());
}
//! [findContact() function]
void AddressBook::findContact()
{
dialog->show();
if (dialog->exec() == QDialog::Accepted) {
QString contactName = dialog->getFindText();
if (contacts.contains(contactName)) {
nameLine->setText(contactName);
addressText->setText(contacts.value(contactName));
} else {
QMessageBox::information(this, tr("Contact Not Found"),
tr("Sorry, \"%1\" is not in your address book.").arg(contactName));
return;
}
}
updateInterface(NavigationMode);
}
//! [findContact() function]
void AddressBook::updateInterface(Mode mode)
{
currentMode = mode;
switch (currentMode) {
case AddingMode:
case EditingMode:
nameLine->setReadOnly(false);
nameLine->setFocus(Qt::OtherFocusReason);
addressText->setReadOnly(false);
addButton->setEnabled(false);
editButton->setEnabled(false);
removeButton->setEnabled(false);
nextButton->setEnabled(false);
previousButton->setEnabled(false);
submitButton->show();
cancelButton->show();
break;
case NavigationMode:
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
int number = contacts.size();
editButton->setEnabled(number >= 1);
removeButton->setEnabled(number >= 1);
findButton->setEnabled(number > 2);
nextButton->setEnabled(number > 1);
previousButton->setEnabled(number > 1);
submitButton->hide();
cancelButton->hide();
break;
}
}

View File

@ -0,0 +1,65 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QMap>
//! [include finddialog's header]
#include "finddialog.h"
//! [include finddialog's header]
QT_BEGIN_NAMESPACE
class QPushButton;
class QLabel;
class QLineEdit;
class QTextEdit;
QT_END_NAMESPACE
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
enum Mode { NavigationMode, AddingMode, EditingMode };
public slots:
void addContact();
void editContact();
void submitContact();
void cancel();
void removeContact();
//! [findContact() declaration]
void findContact();
//! [findContact() declaration]
void next();
void previous();
private:
void updateInterface(Mode mode);
QPushButton *addButton;
QPushButton *editButton;
QPushButton *removeButton;
//! [findButton declaration]
QPushButton *findButton;
//! [findButton declaration]
QPushButton *submitButton;
QPushButton *cancelButton;
QPushButton *nextButton;
QPushButton *previousButton;
QLineEdit *nameLine;
QTextEdit *addressText;
QMap<QString, QString> contacts;
//! [FindDialog declaration]
FindDialog *dialog;
//! [FindDialog declaration]
QString oldName;
QString oldAddress;
Mode currentMode;
};
#endif

View File

@ -0,0 +1,51 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "finddialog.h"
//! [constructor]
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
QLabel *findLabel = new QLabel(tr("Enter the name of a contact:"));
lineEdit = new QLineEdit;
findButton = new QPushButton(tr("&Find"));
findText = "";
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(findLabel);
layout->addWidget(lineEdit);
layout->addWidget(findButton);
setLayout(layout);
setWindowTitle(tr("Find a Contact"));
connect(findButton, &QPushButton::clicked,
this, &FindDialog::findClicked);
connect(findButton, &QPushButton::clicked,
this, &FindDialog::accept);
}
//! [constructor]
//! [findClicked() function]
void FindDialog::findClicked()
{
QString text = lineEdit->text();
if (text.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name."));
return;
} else {
findText = text;
lineEdit->clear();
hide();
}
}
//! [findClicked() function]
//! [getFindText() function]
QString FindDialog::getFindText()
{
return findText;
}
//! [getFindText() function]

View File

@ -0,0 +1,31 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
//! [FindDialog header]
#include <QDialog>
QT_BEGIN_NAMESPACE
class QLineEdit;
class QPushButton;
QT_END_NAMESPACE
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = nullptr);
QString getFindText();
public slots:
void findClicked();
private:
QPushButton *findButton;
QLineEdit *lineEdit;
QString findText;
};
//! [FindDialog header]
#endif

View File

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

View File

@ -0,0 +1,13 @@
QT += widgets
SOURCES = addressbook.cpp \
finddialog.cpp \
main.cpp
HEADERS = addressbook.h \
finddialog.h
QMAKE_PROJECT_NAME = ab_part5
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part5
INSTALLS += target

View File

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

View File

@ -0,0 +1,366 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
nameLine->setReadOnly(true);
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
addressText->setReadOnly(true);
addButton = new QPushButton(tr("&Add"));
editButton = new QPushButton(tr("&Edit"));
editButton->setEnabled(false);
removeButton = new QPushButton(tr("&Remove"));
removeButton->setEnabled(false);
findButton = new QPushButton(tr("&Find"));
findButton->setEnabled(false);
submitButton = new QPushButton(tr("&Submit"));
submitButton->hide();
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->hide();
nextButton = new QPushButton(tr("&Next"));
nextButton->setEnabled(false);
previousButton = new QPushButton(tr("&Previous"));
previousButton->setEnabled(false);
loadButton = new QPushButton(tr("&Load..."));
//! [tooltip 1]
loadButton->setToolTip(tr("Load contacts from a file"));
//! [tooltip 1]
saveButton = new QPushButton(tr("&Save..."));
//! [tooltip 2]
saveButton->setToolTip(tr("Save contacts to a file"));
//! [tooltip 2]
saveButton->setEnabled(false);
dialog = new FindDialog(this);
connect(addButton, &QPushButton::clicked,
this, &AddressBook::addContact);
connect(submitButton, &QPushButton::clicked,
this, &AddressBook::submitContact);
connect(editButton, &QPushButton::clicked,
this, &AddressBook::editContact);
connect(removeButton, &QPushButton::clicked,
this, &AddressBook::removeContact);
connect(cancelButton, &QPushButton::clicked,
this, &AddressBook::cancel);
connect(findButton, &QPushButton::clicked,
this, &AddressBook::findContact);
connect(nextButton, &QPushButton::clicked,
this, &AddressBook::next);
connect(previousButton, &QPushButton::clicked,
this, &AddressBook::previous);
connect(loadButton, &QPushButton::clicked,
this, &AddressBook::loadFromFile);
connect(saveButton, &QPushButton::clicked,
this, &AddressBook::saveToFile);
QVBoxLayout *buttonLayout1 = new QVBoxLayout;
buttonLayout1->addWidget(addButton);
buttonLayout1->addWidget(editButton);
buttonLayout1->addWidget(removeButton);
buttonLayout1->addWidget(findButton);
buttonLayout1->addWidget(submitButton);
buttonLayout1->addWidget(cancelButton);
buttonLayout1->addWidget(loadButton);
buttonLayout1->addWidget(saveButton);
buttonLayout1->addStretch();
QHBoxLayout *buttonLayout2 = new QHBoxLayout;
buttonLayout2->addWidget(previousButton);
buttonLayout2->addWidget(nextButton);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
mainLayout->addLayout(buttonLayout1, 1, 2);
mainLayout->addLayout(buttonLayout2, 2, 1);
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
void AddressBook::addContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
nameLine->clear();
addressText->clear();
updateInterface(AddingMode);
}
void AddressBook::editContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
updateInterface(EditingMode);
}
void AddressBook::submitContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (name.isEmpty() || address.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name and address."));
return;
}
if (currentMode == AddingMode) {
if (!contacts.contains(name)) {
contacts.insert(name, address);
QMessageBox::information(this, tr("Add Successful"),
tr("\"%1\" has been added to your address book.").arg(name));
} else {
QMessageBox::information(this, tr("Add Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (currentMode == EditingMode) {
if (oldName != name) {
if (!contacts.contains(name)) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(oldName));
contacts.remove(oldName);
contacts.insert(name, address);
} else {
QMessageBox::information(this, tr("Edit Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (oldAddress != address) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(name));
contacts[name] = address;
}
}
updateInterface(NavigationMode);
}
void AddressBook::cancel()
{
nameLine->setText(oldName);
addressText->setText(oldAddress);
updateInterface(NavigationMode);
}
void AddressBook::removeContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (contacts.contains(name)) {
int button = QMessageBox::question(this,
tr("Confirm Remove"),
tr("Are you sure you want to remove \"%1\"?").arg(name),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) {
previous();
contacts.remove(name);
QMessageBox::information(this, tr("Remove Successful"),
tr("\"%1\" has been removed from your address book.").arg(name));
}
}
updateInterface(NavigationMode);
}
void AddressBook::next()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i != contacts.end())
i++;
if (i == contacts.end())
i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
void AddressBook::previous()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i == contacts.end()) {
nameLine->clear();
addressText->clear();
return;
}
if (i == contacts.begin())
i = contacts.end();
i--;
nameLine->setText(i.key());
addressText->setText(i.value());
}
void AddressBook::findContact()
{
dialog->show();
if (dialog->exec() == 1) {
QString contactName = dialog->getFindText();
if (contacts.contains(contactName)) {
nameLine->setText(contactName);
addressText->setText(contacts.value(contactName));
} else {
QMessageBox::information(this, tr("Contact Not Found"),
tr("Sorry, \"%1\" is not in your address book.").arg(contactName));
return;
}
}
updateInterface(NavigationMode);
}
void AddressBook::updateInterface(Mode mode)
{
currentMode = mode;
switch (currentMode) {
case AddingMode:
case EditingMode:
nameLine->setReadOnly(false);
nameLine->setFocus(Qt::OtherFocusReason);
addressText->setReadOnly(false);
addButton->setEnabled(false);
editButton->setEnabled(false);
removeButton->setEnabled(false);
nextButton->setEnabled(false);
previousButton->setEnabled(false);
submitButton->show();
cancelButton->show();
loadButton->setEnabled(false);
saveButton->setEnabled(false);
break;
case NavigationMode:
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
int number = contacts.size();
editButton->setEnabled(number >= 1);
removeButton->setEnabled(number >= 1);
findButton->setEnabled(number > 2);
nextButton->setEnabled(number > 1);
previousButton->setEnabled(number > 1);
submitButton->hide();
cancelButton->hide();
loadButton->setEnabled(true);
saveButton->setEnabled(number >= 1);
break;
}
}
//! [saveToFile() function part1]
void AddressBook::saveToFile()
{
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Address Book"), "",
tr("Address Book (*.abk);;All Files (*)"));
//! [saveToFile() function part1]
//! [saveToFile() function part2]
if (fileName.isEmpty())
return;
else {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
//! [saveToFile() function part2]
//! [saveToFile() function part3]
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_5);
out << contacts;
}
}
//! [saveToFile() function part3]
//! [loadFromFile() function part1]
void AddressBook::loadFromFile()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Address Book"), "",
tr("Address Book (*.abk);;All Files (*)"));
//! [loadFromFile() function part1]
//! [loadFromFile() function part2]
if (fileName.isEmpty())
return;
else {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_5);
contacts.clear(); // clear existing contacts
in >> contacts;
//! [loadFromFile() function part2]
//! [loadFromFile() function part3]
if (contacts.isEmpty()) {
QMessageBox::information(this, tr("No contacts in file"),
tr("The file you are attempting to open contains no contacts."));
} else {
QMap<QString, QString>::iterator i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
}
updateInterface(NavigationMode);
}
//! [loadFromFile() function part3]

View File

@ -0,0 +1,66 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QMap>
#include "finddialog.h"
QT_BEGIN_NAMESPACE
class QPushButton;
class QLabel;
class QLineEdit;
class QTextEdit;
QT_END_NAMESPACE
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
enum Mode { NavigationMode, AddingMode, EditingMode };
public slots:
void addContact();
void editContact();
void submitContact();
void cancel();
void removeContact();
void findContact();
void next();
void previous();
//! [save and load functions declaration]
void saveToFile();
void loadFromFile();
//! [save and load functions declaration]
private:
void updateInterface(Mode mode);
QPushButton *addButton;
QPushButton *editButton;
QPushButton *removeButton;
QPushButton *findButton;
QPushButton *submitButton;
QPushButton *cancelButton;
QPushButton *nextButton;
QPushButton *previousButton;
//! [save and load buttons declaration]
QPushButton *loadButton;
QPushButton *saveButton;
//! [save and load buttons declaration]
QLineEdit *nameLine;
QTextEdit *addressText;
QMap<QString, QString> contacts;
FindDialog *dialog;
QString oldName;
QString oldAddress;
Mode currentMode;
};
#endif

View File

@ -0,0 +1,47 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
QLabel *findLabel = new QLabel(tr("Enter the name of a contact:"));
lineEdit = new QLineEdit;
findButton = new QPushButton(tr("&Find"));
findText = "";
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(findLabel);
layout->addWidget(lineEdit);
layout->addWidget(findButton);
setLayout(layout);
setWindowTitle(tr("Find a Contact"));
connect(findButton, &QPushButton::clicked,
this, &FindDialog::findClicked);
connect(findButton, &QPushButton::clicked,
this, &FindDialog::accept);
}
void FindDialog::findClicked()
{
QString text = lineEdit->text();
if (text.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name."));
return;
} else {
findText = text;
lineEdit->clear();
hide();
}
}
QString FindDialog::getFindText()
{
return findText;
}

View File

@ -0,0 +1,31 @@
// 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 QLineEdit;
class QPushButton;
QT_END_NAMESPACE
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = nullptr);
QString getFindText();
public slots:
void findClicked();
private:
QPushButton *findButton;
QLineEdit *lineEdit;
QString findText;
};
#endif

View File

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

View File

@ -0,0 +1,14 @@
QT += widgets
requires(qtConfig(filedialog))
SOURCES = addressbook.cpp \
finddialog.cpp \
main.cpp
HEADERS = addressbook.h \
finddialog.h
QMAKE_PROJECT_NAME = ab_part6
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part6
INSTALLS += target

View File

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

View File

@ -0,0 +1,419 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "addressbook.h"
AddressBook::AddressBook(QWidget *parent)
: QWidget(parent)
{
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLine = new QLineEdit;
nameLine->setReadOnly(true);
QLabel *addressLabel = new QLabel(tr("Address:"));
addressText = new QTextEdit;
addressText->setReadOnly(true);
addButton = new QPushButton(tr("&Add"));
editButton = new QPushButton(tr("&Edit"));
editButton->setEnabled(false);
removeButton = new QPushButton(tr("&Remove"));
removeButton->setEnabled(false);
findButton = new QPushButton(tr("&Find"));
findButton->setEnabled(false);
submitButton = new QPushButton(tr("&Submit"));
submitButton->hide();
cancelButton = new QPushButton(tr("&Cancel"));
cancelButton->hide();
nextButton = new QPushButton(tr("&Next"));
nextButton->setEnabled(false);
previousButton = new QPushButton(tr("&Previous"));
previousButton->setEnabled(false);
loadButton = new QPushButton(tr("&Load..."));
loadButton->setToolTip(tr("Load contacts from a file"));
saveButton = new QPushButton(tr("&Save..."));
saveButton->setToolTip(tr("Save contacts to a file"));
saveButton->setEnabled(false);
exportButton = new QPushButton(tr("E&xport"));
exportButton->setToolTip(tr("Export as vCard"));
exportButton->setEnabled(false);
dialog = new FindDialog(this);
connect(addButton, &QPushButton::clicked,
this, &AddressBook::addContact);
connect(submitButton, &QPushButton::clicked,
this, &AddressBook::submitContact);
connect(editButton, &QPushButton::clicked,
this, &AddressBook::editContact);
connect(removeButton, &QPushButton::clicked,
this, &AddressBook::removeContact);
connect(cancelButton, &QPushButton::clicked,
this, &AddressBook::cancel);
connect(findButton, &QPushButton::clicked,
this, &AddressBook::findContact);
connect(nextButton, &QPushButton::clicked,
this, &AddressBook::next);
connect(previousButton, &QPushButton::clicked,
this, &AddressBook::previous);
connect(loadButton, &QPushButton::clicked,
this, &AddressBook::loadFromFile);
connect(saveButton, &QPushButton::clicked,
this, &AddressBook::saveToFile);
connect(exportButton, &QPushButton::clicked,
this, &AddressBook::exportAsVCard);
QVBoxLayout *buttonLayout1 = new QVBoxLayout;
buttonLayout1->addWidget(addButton);
buttonLayout1->addWidget(editButton);
buttonLayout1->addWidget(removeButton);
buttonLayout1->addWidget(findButton);
buttonLayout1->addWidget(submitButton);
buttonLayout1->addWidget(cancelButton);
buttonLayout1->addWidget(loadButton);
buttonLayout1->addWidget(saveButton);
buttonLayout1->addWidget(exportButton);
buttonLayout1->addStretch();
QHBoxLayout *buttonLayout2 = new QHBoxLayout;
buttonLayout2->addWidget(previousButton);
buttonLayout2->addWidget(nextButton);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);
mainLayout->addLayout(buttonLayout1, 1, 2);
mainLayout->addLayout(buttonLayout2, 2, 1);
setLayout(mainLayout);
setWindowTitle(tr("Simple Address Book"));
}
void AddressBook::addContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
nameLine->clear();
addressText->clear();
updateInterface(AddingMode);
}
void AddressBook::editContact()
{
oldName = nameLine->text();
oldAddress = addressText->toPlainText();
updateInterface(EditingMode);
}
void AddressBook::submitContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (name.isEmpty() || address.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name and address."));
return;
}
if (currentMode == AddingMode) {
if (!contacts.contains(name)) {
contacts.insert(name, address);
QMessageBox::information(this, tr("Add Successful"),
tr("\"%1\" has been added to your address book.").arg(name));
} else {
QMessageBox::information(this, tr("Add Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (currentMode == EditingMode) {
if (oldName != name) {
if (!contacts.contains(name)) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(oldName));
contacts.remove(oldName);
contacts.insert(name, address);
} else {
QMessageBox::information(this, tr("Edit Unsuccessful"),
tr("Sorry, \"%1\" is already in your address book.").arg(name));
}
} else if (oldAddress != address) {
QMessageBox::information(this, tr("Edit Successful"),
tr("\"%1\" has been edited in your address book.").arg(name));
contacts[name] = address;
}
}
updateInterface(NavigationMode);
}
void AddressBook::cancel()
{
nameLine->setText(oldName);
addressText->setText(oldAddress);
updateInterface(NavigationMode);
}
void AddressBook::removeContact()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
if (contacts.contains(name)) {
int button = QMessageBox::question(this,
tr("Confirm Remove"),
tr("Are you sure you want to remove \"%1\"?").arg(name),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes) {
previous();
contacts.remove(name);
QMessageBox::information(this, tr("Remove Successful"),
tr("\"%1\" has been removed from your address book.").arg(name));
}
}
updateInterface(NavigationMode);
}
void AddressBook::next()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i != contacts.end())
i++;
if (i == contacts.end())
i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
void AddressBook::previous()
{
QString name = nameLine->text();
QMap<QString, QString>::iterator i = contacts.find(name);
if (i == contacts.end()) {
nameLine->clear();
addressText->clear();
return;
}
if (i == contacts.begin())
i = contacts.end();
i--;
nameLine->setText(i.key());
addressText->setText(i.value());
}
void AddressBook::findContact()
{
dialog->show();
if (dialog->exec() == 1) {
QString contactName = dialog->getFindText();
if (contacts.contains(contactName)) {
nameLine->setText(contactName);
addressText->setText(contacts.value(contactName));
} else {
QMessageBox::information(this, tr("Contact Not Found"),
tr("Sorry, \"%1\" is not in your address book.").arg(contactName));
return;
}
}
updateInterface(NavigationMode);
}
void AddressBook::updateInterface(Mode mode)
{
currentMode = mode;
switch (currentMode) {
case AddingMode:
case EditingMode:
nameLine->setReadOnly(false);
nameLine->setFocus(Qt::OtherFocusReason);
addressText->setReadOnly(false);
addButton->setEnabled(false);
editButton->setEnabled(false);
removeButton->setEnabled(false);
nextButton->setEnabled(false);
previousButton->setEnabled(false);
submitButton->show();
cancelButton->show();
loadButton->setEnabled(false);
saveButton->setEnabled(false);
exportButton->setEnabled(false);
break;
case NavigationMode:
if (contacts.isEmpty()) {
nameLine->clear();
addressText->clear();
}
nameLine->setReadOnly(true);
addressText->setReadOnly(true);
addButton->setEnabled(true);
int number = contacts.size();
editButton->setEnabled(number >= 1);
removeButton->setEnabled(number >= 1);
findButton->setEnabled(number > 2);
nextButton->setEnabled(number > 1);
previousButton->setEnabled(number > 1);
submitButton->hide();
cancelButton->hide();
exportButton->setEnabled(number >= 1);
loadButton->setEnabled(true);
saveButton->setEnabled(number >= 1);
break;
}
}
void AddressBook::saveToFile()
{
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Address Book"), "",
tr("Address Book (*.abk);;All Files (*)"));
if (fileName.isEmpty())
return;
else {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_3);
out << contacts;
}
updateInterface(NavigationMode);
}
void AddressBook::loadFromFile()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Address Book"), "",
tr("Address Book (*.abk);;All Files (*)"));
if (fileName.isEmpty())
return;
else {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_3);
in >> contacts;
QMap<QString, QString>::iterator i = contacts.begin();
nameLine->setText(i.key());
addressText->setText(i.value());
}
updateInterface(NavigationMode);
}
//! [export function part1]
void AddressBook::exportAsVCard()
{
QString name = nameLine->text();
QString address = addressText->toPlainText();
QString firstName;
QString lastName;
QStringList nameList;
int index = name.indexOf(" ");
if (index != -1) {
nameList = name.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
firstName = nameList.first();
lastName = nameList.last();
} else {
firstName = name;
lastName = "";
}
QString fileName = QFileDialog::getSaveFileName(this,
tr("Export Contact"), "",
tr("vCard Files (*.vcf);;All Files (*)"));
if (fileName.isEmpty())
return;
QFile file(fileName);
//! [export function part1]
//! [export function part2]
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QTextStream out(&file);
//! [export function part2]
//! [export function part3]
out << "BEGIN:VCARD" << '\n';
out << "VERSION:2.1" << '\n';
out << "N:" << lastName << ';' << firstName << '\n';
if (!nameList.isEmpty())
out << "FN:" << nameList.join(' ') << '\n';
else
out << "FN:" << firstName << '\n';
//! [export function part3]
//! [export function part4]
address.replace(";", "\\;", Qt::CaseInsensitive);
address.replace('\n', ";", Qt::CaseInsensitive);
address.replace(",", " ", Qt::CaseInsensitive);
out << "ADR;HOME:;" << address << '\n';
out << "END:VCARD" << '\n';
QMessageBox::information(this, tr("Export Successful"),
tr("\"%1\" has been exported as a vCard.").arg(name));
}
//! [export function part4]

View File

@ -0,0 +1,68 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QMap>
#include "finddialog.h"
QT_BEGIN_NAMESPACE
class QPushButton;
class QLabel;
class QLineEdit;
class QTextEdit;
QT_END_NAMESPACE
class AddressBook : public QWidget
{
Q_OBJECT
public:
AddressBook(QWidget *parent = nullptr);
enum Mode { NavigationMode, AddingMode, EditingMode };
public slots:
void addContact();
void editContact();
void submitContact();
void cancel();
void removeContact();
void findContact();
void next();
void previous();
void saveToFile();
void loadFromFile();
//! [exportAsVCard() declaration]
void exportAsVCard();
//! [exportAsVCard() declaration]
private:
void updateInterface(Mode mode);
QPushButton *addButton;
QPushButton *editButton;
QPushButton *removeButton;
QPushButton *findButton;
QPushButton *submitButton;
QPushButton *cancelButton;
QPushButton *nextButton;
QPushButton *previousButton;
QPushButton *loadButton;
QPushButton *saveButton;
//! [exportButton declaration]
QPushButton *exportButton;
//! [exportButton declaration]
QLineEdit *nameLine;
QTextEdit *addressText;
QMap<QString, QString> contacts;
FindDialog *dialog;
QString oldName;
QString oldAddress;
Mode currentMode;
};
#endif

View File

@ -0,0 +1,47 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
QLabel *findLabel = new QLabel(tr("Enter the name of a contact:"));
lineEdit = new QLineEdit;
findButton = new QPushButton(tr("&Find"));
findText = "";
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(findLabel);
layout->addWidget(lineEdit);
layout->addWidget(findButton);
setLayout(layout);
setWindowTitle(tr("Find a Contact"));
connect(findButton, &QPushButton::clicked,
this, &FindDialog::findClicked);
connect(findButton, &QPushButton::clicked,
this, &FindDialog::accept);
}
void FindDialog::findClicked()
{
QString text = lineEdit->text();
if (text.isEmpty()) {
QMessageBox::information(this, tr("Empty Field"),
tr("Please enter a name."));
return;
} else {
findText = text;
lineEdit->clear();
hide();
}
}
QString FindDialog::getFindText()
{
return findText;
}

View File

@ -0,0 +1,31 @@
// 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 QLineEdit;
class QPushButton;
QT_END_NAMESPACE
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = nullptr);
QString getFindText();
public slots:
void findClicked();
private:
QPushButton *findButton;
QLineEdit *lineEdit;
QString findText;
};
#endif

View File

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

View File

@ -0,0 +1,14 @@
QT += widgets
requires(qtConfig(filedialog))
SOURCES = addressbook.cpp \
finddialog.cpp \
main.cpp
HEADERS = addressbook.h \
finddialog.h
QMAKE_PROJECT_NAME = ab_part7
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook/part7
INSTALLS += target

View File

@ -0,0 +1 @@
add_subdirectory(gsQt)

View File

@ -0,0 +1,4 @@
TEMPLATE = subdirs
SUBDIRS += dir_gsqt
dir_gsqt.file = gsQt/gsqt.pro

View File

@ -0,0 +1,8 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
qt_internal_add_example(part1)
qt_internal_add_example(part2)
qt_internal_add_example(part3)
qt_internal_add_example(part4)
qt_internal_add_example(part5)

View File

@ -0,0 +1,7 @@
TEMPLATE = subdirs
SUBDIRS = part1 \
part2 \
part3 \
part4 \
part5

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(getting_started_part1 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/gettingStarted/gsQt/part1")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(getting_started_part1
main.cpp
)
set_target_properties(getting_started_part1 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(getting_started_part1 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS getting_started_part1
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

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

View File

@ -0,0 +1,8 @@
QT += widgets
SOURCES = main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/gettingStarted/gsQt/part1
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(getting_started_part2 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/gettingStarted/gsQt/part2")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(getting_started_part2
main.cpp
)
set_target_properties(getting_started_part2 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(getting_started_part2 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS getting_started_part2
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,27 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextEdit *textEdit = new QTextEdit;
QPushButton *quitButton = new QPushButton("&Quit");
QObject::connect(quitButton, &QPushButton::clicked,
qApp, &QApplication::quit);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(textEdit);
layout->addWidget(quitButton);
QWidget window;
window.setLayout(layout);
window.show();
return app.exec();
}

View File

@ -0,0 +1,8 @@
QT += widgets
SOURCES = main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/gettingStarted/gsQt/part2
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(getting_started_part3 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/gettingStarted/gsQt/part3")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(getting_started_part3
main.cpp
)
set_target_properties(getting_started_part3 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(getting_started_part3 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS getting_started_part3
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,61 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
class Notepad : public QWidget
{
Q_OBJECT
public:
Notepad();
private slots:
void quit();
private:
QTextEdit *textEdit;
QPushButton *quitButton;
};
Notepad::Notepad()
{
textEdit = new QTextEdit;
quitButton = new QPushButton(tr("Quit"));
connect(quitButton, &QPushButton::clicked,
this, &Notepad::quit);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(textEdit);
layout->addWidget(quitButton);
setLayout(layout);
setWindowTitle(tr("Notepad"));
}
void Notepad::quit()
{
QMessageBox messageBox;
messageBox.setWindowTitle(tr("Notepad"));
messageBox.setText(tr("Do you really want to quit?"));
messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
messageBox.setDefaultButton(QMessageBox::No);
if (messageBox.exec() == QMessageBox::Yes)
qApp->quit();
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Notepad notepad;
notepad.show();
return app.exec();
}
#include "main.moc"

View File

@ -0,0 +1,8 @@
QT += widgets
SOURCES = main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/gettingStarted/gsQt/part3
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(getting_started_part4 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/gettingStarted/gsQt/part4")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(getting_started_part4
main.cpp
)
set_target_properties(getting_started_part4 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(getting_started_part4 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS getting_started_part4
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,73 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
class Notepad : public QMainWindow
{
Q_OBJECT
public:
Notepad();
private slots:
void load();
void save();
private:
QTextEdit *textEdit;
QAction *loadAction;
QAction *saveAction;
QAction *exitAction;
QMenu *fileMenu;
};
Notepad::Notepad()
{
loadAction = new QAction(tr("&Load"), this);
saveAction = new QAction(tr("&Save"), this);
exitAction = new QAction(tr("E&xit"), this);
connect(loadAction, &QAction::triggered,
this, &Notepad::load);
connect(saveAction, &QAction::triggered,
this, &Notepad::save);
connect(exitAction, &QAction::triggered,
qApp, &QApplication::quit);
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(loadAction);
fileMenu->addAction(saveAction);
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
textEdit = new QTextEdit;
setCentralWidget(textEdit);
setWindowTitle(tr("Notepad"));
}
void Notepad::load()
{
}
void Notepad::save()
{
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Notepad notepad;
notepad.show();
return app.exec();
};
#include "main.moc"

View File

@ -0,0 +1,8 @@
QT += widgets
SOURCES = main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/gettingStarted/gsQt/part4
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(getting_started_part5 LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/gettingStarted/gsQt/part5")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(getting_started_part5
main.cpp
)
set_target_properties(getting_started_part5 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(getting_started_part5 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS getting_started_part5
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>
class Notepad : public QMainWindow
{
Q_OBJECT
public:
Notepad();
private slots:
void open();
void save();
private:
QTextEdit *textEdit;
QAction *openAction;
QAction *saveAction;
QAction *exitAction;
QMenu *fileMenu;
};
Notepad::Notepad()
{
openAction = new QAction(tr("&Load"), this);
saveAction = new QAction(tr("&Save"), this);
exitAction = new QAction(tr("E&xit"), this);
connect(openAction, &QAction::triggered,
this, &Notepad::open);
connect(saveAction, &QAction::triggered,
this, &Notepad::save);
connect(exitAction, &QAction::triggered,
qApp, &QApplication::quit);
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAction);
fileMenu->addAction(saveAction);
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
textEdit = new QTextEdit;
setCentralWidget(textEdit);
setWindowTitle(tr("Notepad"));
}
void Notepad::open()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream in(&file);
textEdit->setText(in.readAll());
file.close();
}
}
void Notepad::save()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "",
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
} else {
QTextStream stream(&file);
stream << textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Notepad notepad;
notepad.show();
return app.exec();
}
#include "main.moc"

View File

@ -0,0 +1,8 @@
QT += widgets
requires(qtConfig(filedialog))
SOURCES = main.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/gettingStarted/gsQt/part5
INSTALLS += target

View File

@ -0,0 +1,504 @@
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\example tutorials/notepad
\title Getting Started Programming with Qt Widgets
\brief A tutorial for Qt Widgets based notepad application.
In this topic, we teach basic Qt knowledge by implementing a simple
Notepad application using C++ and the \l{Qt Widgets} module. The
application is a small text editor which allows you to create a text
file, save it, print it,
or reopen and edit it again. You can also set the font to be used.
\image notepad1.png "Notepad application"
\include examples-run.qdocinc
\section1 Creating the Notepad Project
Setting up a new project in Qt Creator is aided by a wizard that
guides you step-by-step through the project creation process. The
wizard prompts you to enter the settings needed for that particular
type of project and creates the project for you.
\note The UI text in Qt Creator and the contents of the generated files
depend on the Qt Creator version that you use.
\image notepad2.png "Qt Creator New Project dialog"
To create the Notepad project, select \uicontrol File >
\uicontrol {New Project} > \uicontrol {Application (Qt)} >
\uicontrol {Qt Widgets Application} > \uicontrol Choose, and follow the
instructions of the wizard. In the \uicontrol{Class Information} dialog,
type \e Notepad as the class name and select \uicontrol QMainWindow
as the base class.
\image notepad3.png "Class Information Dialog"
The \uicontrol {Qt Widgets Application} wizard creates a project that contains
a main source file and a set of files that specify a user interface
(Notepad widget):
\list
\li CMakeLists.txt - the project file.
\li main.cpp - the main source file for the application.
\li notepad.cpp - the source file of the notepad class of the
Notepad widget.
\li notepad.h - the header file of the notepad class for the
Notepad widget.
\li notepad.ui - the UI form for the Notepad widget.
\endlist
The files come with the necessary boiler plate code for you to be able to
build and run the project. We will take a closer look at the file contents
in the following sections.
\b{Learn More}
\table
\header
\li About
\li Here
\row
\li Using Qt Creator
\li \l{Qt Creator Manual}{Qt Creator}
\row
\li Creating other kind of applications with Qt Creator
\li \l{Qt Creator: Tutorials}{Qt Creator Tutorials}
\endtable
\section1 Main Source File
The wizard generates the following code in the main.cpp file:
\quotefromfile tutorials/notepad/main.cpp
\skipto "notepad.h"
\printuntil }
We will go through the code line by line. The following lines include
the header files for the Notepad widget and QApplication. All Qt classes
have a header file named after them.
\quotefromfile tutorials/notepad/main.cpp
\skipto notepad.h
\printuntil QApplication
The following line defines the main function that is the entry point
for all C and C++ based applications:
\printline main
The following line creates a QApplication object. This object manages
application-wide resources and is necessary to run any Qt program
that uses Qt Widgets. It constructs an application object with \c argc
command line arguments run in \c argv. (For GUI applications that
do not use Qt Widgets, you can use QGuiApplication instead.)
\skipuntil {
\printuntil QApplication
The following line creates the Notepad object. This is the object for
which the wizard created the class and the UI file. The user interface
contains visual elements that are called \c widgets in Qt. Examples
of widgets are text edits, scroll bars, labels, and radio buttons. A
widget can also be a container for other widgets; a dialog or a main
application window, for example.
\printline Notepad
The following line shows the Notepad widget on the screen in its own
window. Widgets can also function as containers. An example of this
is QMainWindow which often contains several types of widgets. Widgets
are not visible by default; the function \l{QWidget::}{show()} makes
the widget visible.
\printline w.show
The following line makes the QApplication enter its event loop. When
a Qt application is running, events are generated and sent to the
widgets of the application. Examples of events are mouse presses
and key strokes.
\printline a.exec
\b{Learn More}
\table
\header
\li About
\li Here
\row
\li Widgets and Window Geometry
\li \l{Window and Dialog Widgets}
\row
\li Events and event handling
\li \l{The Event System}
\endtable
\section1 Designing a UI
The wizard generates a user interface definition in XML format: notepad.ui.
When you open the notepad.ui file in Qt Creator, it automatically
opens in the integrated Qt Designer.
When you build the application, Qt Creator launches the Qt
\l{User Interface Compiler (uic)} that reads the .ui file and creates
a corresponding C++ header file, ui_notepad.h.
\section2 Using Qt Designer
The wizard creates an application that uses a QMainWindow. It has
its own layout to which you can add a menu bar, dock widgets, toolbars,
and a status bar. The center area can be occupied by any kind of widget.
The wizard places the Notepad widget there.
To add widgets in Qt Designer:
\list 1
\li In the Qt Creator \uicontrol Edit mode, double-click the notepad.ui
file in the \uicontrol Projects view to launch the file in the integrated
Qt Designer.
\li Drag and drop widgets Text Edit (QTextEdit) to the form.
\li Press \key {Ctrl+A} (or \key {Cmd+A}) to select the widgets and click
\uicontrol {Lay out Vertically} (or press \key {Ctrl+L}) to apply a vertical
layout (QVBoxLayout).
\li Press \key {Ctrl+S} (or \key {Cmd+S}) to save your changes.
\endlist
The UI now looks as follows in Qt Designer:
\image notepad4.png
You can view the generated XML file in the code editor:
\quotefromfile tutorials/notepad/notepad.ui
\printuntil QMenuBar
\dots
The following line contains the XML declaration, which specifies the
XML version and character encoding used in the document:
\code
<?xml version="1.0" encoding="UTF-8"?>
\endcode
The rest of the file specifies an \c ui element that defines a
Notepad widget:
\code
<ui version="4.0">
\endcode
The UI file is used together with the header and source file of the
Notepad class. We will look at the rest of the UI file in the later
sections.
\section2 Notepad Header File
The wizard generated a header file for the Notepad class that has the
necessary #includes, a constructor, a destructor, and the Ui object.
The file looks as follows:
\quotefromfile tutorials/notepad/notepad.h
\skipto #include
\printuntil ~Notepad();
\skipto private:
\printuntil };
The following line includes QMainWindow that provides a main application
window:
\quotefromfile tutorials/notepad/notepad.h
\skipto #include
\printuntil >
The following lines declare the Notepad class in the Ui namespace,
which is the standard namespace for the UI classes generated from
.ui files by the \c uic tool:
\skipto Ui {
\printuntil }
The class declaration contains the \c Q_OBJECT macro. It must come
first in the class definition, and declares our class as a QObject.
Naturally, it must also inherit from QObject. A QObject adds several
abilities to a normal C++ class. Notably, the class name and slot
names can be queried at runtime. It is also possible to query a slot's
parameter types and invoke it.
\skipto class Notepad
\printuntil Q_OBJECT
The following lines declare a constructor that has a default argument
called \c parent.
The value 0 indicates that the widget has no parent (it is a top-level
widget).
\printuntil explicit
The following line declares a virtual destructor to free the resources
that were acquired by the object during its life-cycle. According to
the C++ naming convention, destructors have the same name as the class
they are associated with, prefixed with a tilde (~). In QObject,
destructors are virtual to ensure that the destructors of derived
classes are invoked properly when an object is deleted through a
pointer-to-base-class.
\printuntil ~Notepad();
The following lines declare a member variable which is a pointer to
the Notepad UI class. A member variable is associated with a specific
class, and accessible for all its methods.
\skipto private:
\printuntil };
\section2 Notepad Source File
The source file that the wizard generated for the Notepad class looks
as follows:
\quotefromfile tutorials/notepad/notepad.cpp
\skipto #include "notepad.h"
\printuntil ui->setupUi(this);
\skipto }
\printuntil }
The following lines include the Notepad class header file that was
generated by the wizard and the UI header file that was generated
by the \c uic tool:
\quotefromfile tutorials/notepad/notepad.cpp
\skipto #include "notepad.h"
\printuntil #include "ui_notepad.h"
The following line defines the \c {Notepad} constructor:
\printuntil Notepad::Notepad
The following line calls the QMainWindow constructor, which is
the base class for the Notepad class:
\printuntil QMainWindow
The following line creates the UI class instance and assigns it to
the \c ui member:
\printline ui(new
The following line sets up the UI:
\printuntil ui->setupUi(this)
In the destructor, we delete the \c ui:
\skipto Notepad::~Notepad
\printuntil }
\section2 Project File
The wizard generates the following project file, \c CMakeLists.txt, for
us:
\quotefile tutorials/notepad/CMakeLists.txt
The project file specifies the source, header, and UI files included in
the project.
\b{Learn More}
\table
\header
\li About
\li Here
\row
\li Using Qt Designer
\li \l{Qt Designer Manual}
\row
\li Layouts
\li \l{Layout Management},
\l{Widgets and Layouts},
\l{Layout Examples}
\row
\li The widgets that come with Qt
\li \l{Qt Widget Gallery}
\row
\li Main windows and main window classes
\li \l{Application Main Window},
\l{Main Window Examples}
\row
\li QObjects and the Qt Object model (This is essential to
understand Qt)
\li \l{Object Model}
\row
\li qmake and the Qt build system
\li \l{qmake Manual}
\endtable
\section1 Adding User Interaction
To add functionality to the editor, we start by adding menu items
and buttons on a toolbar.
Click on "Type Here", and add the options New, Open, Save, Save as,
Print and Exit. This creates 5 lines in the Action Editor below.
To connect the actions to slots, right-click an action and select
\uicontrol {Go to slot} > \uicontrol triggered(), and complete the
code for that given slot.
If we also want to add the actions to a toolbar, we can assign an
icon to each QAction, and then drag the QAction to the toolbar. You
assign an icon by entering an icon name in the Icon property of the
action concerned. When the QAction has been dragged to the toolbar,
clicking the icon will launch the associated slot.
Complete the method \c newDocument():
\quotefromfile tutorials/notepad/notepad.cpp
\skipto newDocument()
\printuntil }
The \c currentFile variable is a global variable containing the file
presently being edited, and \c clear() clears the text buffer.
The \c currentFile variable is defined in the private part of notepad.h:
\quotefromfile tutorials/notepad/notepad.h
\skipto private:
\printuntil currentFile;
\section2 Opening a file
In \c notepad.ui, right click on \c actionOpen and select
\uicontrol {Go to Slot}.
Complete method \c open().
\quotefromfile tutorials/notepad/notepad.cpp
\skipto open()
\printuntil file.close
\printuntil }
\c QFileDialog::getOpenFileName opens a dialog enabling you to select
a file. QFile object \c myfile has the selected \c file_name as
parameter. We store the selected file also into the global variable
\c currentFile for later purposes. We open the file with \c file.open
as a readonly text file. If it cannot be opened, a warning is issued,
and the program stops.
We define a QTextStream \c instream for parameter \c myfile.
The contents of file \c myfile is copied into QString \c text.
\c setText(text) fills the buffer of our editor with \c text.
\section2 Saving a file
We create the method for saving a file in the same way as for
\l {Opening a file}, by right clicking on \c actionSave, and
selecting \uicontrol {Go to Slot}.
\skipto Notepad::save
\printuntil file.close
\printuntil }
QFile object \c myfile is linked to global variable \c current_file,
the variable that contains the file we were working with.
If we cannot open \c myfile, an error message is issued and the
method stops. We create a QTextStream \c outstream. The contents
of the editor buffer is converted to plain text, and then written
to \c outstream.
\section2 Saving a file under another name
\skipto Notepad::saveAs
\printuntil file.close
\printuntil }
This is the same procedure as for \l {Saving a file}, the only
difference being that here you need to enter a new file name for
the file to be created.
\section2 Printing a File
If you want to use print functionalities, you need to add
\c PrintSupport to the project file:
\quotefromfile tutorials/notepad/CMakeLists.txt
\skipto find_package(Qt6
\printuntil )
In \c notepad.cpp, we declare a QPrinter object called \c printDev:
\quotefromfile tutorials/notepad/notepad.cpp
\skipto void Notepad::print()
\printuntil }
We launch a printer dialog box and store the selected printer in
object \c printDev. If we clicked on \c Cancel and did not select
a printer, the methods returns. The actual printer command is given
with \c ui->textEdit->print with our QPrinter object as parameter.
\section2 Select a Font
\skipto Notepad::selectFont
\printuntil }
We declare a boolean indicating if we did select a font with
QFontDialog. If so, we set the font with \c ui->textEdit->setFont(myfont).
\section2 Copy, Cut, Paste, Undo, and Redo
If you select some text, and want to copy it to the clipboard,
you call the appropriate method of \c ui->textEdit. The same counts
for cut, paste, undo, and redo.
This table shows the method name to use.
\table
\header
\li Task
\li Method called
\row
\li Copy
\li ui->textEdit->copy()
\row
\li Cut
\li ui->textEdit->cut()
\row
\li Paste
\li ui->textEdit->paste()
\row
\li Undo
\li ui->textEdit->undo()
\row
\li Redo
\li ui->textEdit->redo()
\endtable
\b{Learn More}
\table
\header
\li About
\li Here
\row
\li MDI applications
\li QMdiArea,
\l{MDI Example}
\row
\li Files and I/O devices
\li QFile, QIODevice
\row
\li tr() and internationalization
\li \l{Qt Linguist Manual},
\l{Writing Source Code for Translation},
\l{Internationalization with Qt}
\endtable
\include cli-build-cmake.qdocinc cli-build-cmake
*/

View File

@ -0,0 +1,16 @@
TARGET = mv_readonly
TEMPLATE = app
QT += widgets
requires(qtConfig(tableview))
SOURCES += main.cpp \
mymodel.cpp
HEADERS += mymodel.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/1_readonly
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(mv_readonly LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/modelview/1_readonly")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(mv_readonly
main.cpp
mymodel.cpp mymodel.h
)
set_target_properties(mv_readonly PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(mv_readonly PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS mv_readonly
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,19 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [Quoting ModelView Tutorial]
// main.cpp
#include <QApplication>
#include <QTableView>
#include "mymodel.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
MyModel myModel;
tableView.setModel(&myModel);
tableView.show();
return a.exec();
}
//! [Quoting ModelView Tutorial]

View File

@ -0,0 +1,32 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [Quoting ModelView Tutorial]
// mymodel.cpp
#include "mymodel.h"
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
int MyModel::rowCount(const QModelIndex & /*parent*/) const
{
return 2;
}
int MyModel::columnCount(const QModelIndex & /*parent*/) const
{
return 3;
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole)
return QString("Row%1, Column%2")
.arg(index.row() + 1)
.arg(index.column() +1);
return QVariant();
}
//! [Quoting ModelView Tutorial]

View File

@ -0,0 +1,23 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MYMODEL_H
#define MYMODEL_H
//! [Quoting ModelView Tutorial]
// mymodel.h
#include <QAbstractTableModel>
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
};
//! [Quoting ModelView Tutorial]
#endif // MYMODEL_H

View File

@ -0,0 +1,15 @@
TARGET = mv_formatting
TEMPLATE = app
QT += widgets
requires(qtConfig(tableview))
SOURCES += main.cpp \
mymodel.cpp
HEADERS += mymodel.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/2_formatting
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(mv_formatting LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/modelview/2_formatting")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(mv_formatting
main.cpp
mymodel.cpp mymodel.h
)
set_target_properties(mv_formatting PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(mv_formatting PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS mv_formatting
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

@ -0,0 +1,19 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [Quoting ModelView Tutorial]
// main.cpp
#include <QApplication>
#include <QTableView>
#include "mymodel.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
MyModel myModel;
tableView.setModel(&myModel);
tableView.show();
return a.exec();
}
//! [Quoting ModelView Tutorial]

View File

@ -0,0 +1,65 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "mymodel.h"
#include <QFont>
#include <QBrush>
#include <QDebug>
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
int MyModel::rowCount(const QModelIndex & /*parent */) const
{
return 2;
}
int MyModel::columnCount(const QModelIndex & /*parent */) const
{
return 3;
}
//! [Quoting ModelView Tutorial]
// mymodel.cpp
QVariant MyModel::data(const QModelIndex &index, int role) const
{
int row = index.row();
int col = index.column();
// generate a log message when this method gets called
qDebug() << QString("row %1, col%2, role %3")
.arg(row).arg(col).arg(role);
switch (role) {
case Qt::DisplayRole:
if (row == 0 && col == 1) return QString("<--left");
if (row == 1 && col == 1) return QString("right-->");
return QString("Row%1, Column%2")
.arg(row + 1)
.arg(col +1);
case Qt::FontRole:
if (row == 0 && col == 0) { // change font only for cell(0,0)
QFont boldFont;
boldFont.setBold(true);
return boldFont;
}
break;
case Qt::BackgroundRole:
if (row == 1 && col == 2) // change background only for cell(1,2)
return QBrush(Qt::red);
break;
case Qt::TextAlignmentRole:
if (row == 1 && col == 1) // change text alignment only for cell(1,1)
return int(Qt::AlignRight | Qt::AlignVCenter);
break;
case Qt::CheckStateRole:
if (row == 1 && col == 0) // add a checkbox to cell(1,0)
return Qt::Checked;
break;
}
return QVariant();
}
//! [Quoting ModelView Tutorial]

View File

@ -0,0 +1,20 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QAbstractTableModel>
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
};
#endif // MYMODEL_H

View File

@ -0,0 +1,15 @@
TARGET = mv_changingmodel
TEMPLATE = app
QT += widgets
requires(qtConfig(tableview))
SOURCES += main.cpp \
mymodel.cpp
HEADERS += mymodel.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/3_changingmodel
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(mv_changingmodel LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/modelview/3_changingmodel")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(mv_changingmodel
main.cpp
mymodel.cpp mymodel.h
)
set_target_properties(mv_changingmodel PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(mv_changingmodel PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS mv_changingmodel
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

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 <QTableView>
#include "mymodel.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
MyModel myModel;
tableView.setModel(&myModel);
tableView.show();
return a.exec();
}

View File

@ -0,0 +1,52 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "mymodel.h"
#include <QTime>
//! [quoting mymodel_a]
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
, timer(new QTimer(this))
{
timer->setInterval(1000);
connect(timer, &QTimer::timeout , this, &MyModel::timerHit);
timer->start();
}
//! [quoting mymodel_a]
//-------------------------------------------------------
int MyModel::rowCount(const QModelIndex & /*parent */) const
{
return 2;
}
//-------------------------------------------------------
int MyModel::columnCount(const QModelIndex & /*parent */) const
{
return 3;
}
//-------------------------------------------------------
//! [quoting mymodel_QVariant ]
QVariant MyModel::data(const QModelIndex &index, int role) const
{
int row = index.row();
int col = index.column();
if (role == Qt::DisplayRole && row == 0 && col == 0)
return QTime::currentTime().toString();
return QVariant();
}
//! [quoting mymodel_QVariant ]
//-------------------------------------------------------
//! [quoting mymodel_b ]
void MyModel::timerHit()
{
// we identify the top left cell
QModelIndex topLeft = createIndex(0,0);
// emit a signal to make the view reread identified data
emit dataChanged(topLeft, topLeft, {Qt::DisplayRole});
}
//! [quoting mymodel_b ]

View File

@ -0,0 +1,27 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QAbstractTableModel>
#include <QTimer>
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
private slots:
void timerHit();
private:
QTimer *timer;
};
#endif // MYMODEL_H

View File

@ -0,0 +1,15 @@
TARGET = mv_headers
TEMPLATE = app
QT += widgets
requires(qtConfig(tableview))
SOURCES += main.cpp \
mymodel.cpp
HEADERS += mymodel.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/4_headers
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(mv_headers LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/modelview/4_headers")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(mv_headers
main.cpp
mymodel.cpp mymodel.h
)
set_target_properties(mv_headers PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(mv_headers PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS mv_headers
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

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 <QTableView>
#include "mymodel.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
MyModel myModel;
tableView.setModel(&myModel);
tableView.show();
return a.exec();
}

View File

@ -0,0 +1,49 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "mymodel.h"
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
//-------------------------------------------------------
int MyModel::rowCount(const QModelIndex & /*parent*/) const
{
return 2;
}
//-------------------------------------------------------
int MyModel::columnCount(const QModelIndex & /*parent*/) const
{
return 3;
}
//-------------------------------------------------------
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
return QString("Row%1, Column%2")
.arg(index.row() + 1)
.arg(index.column() +1);
}
return QVariant();
}
//! [quoting mymodel_c]
QVariant MyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
switch (section) {
case 0:
return QString("first");
case 1:
return QString("second");
case 2:
return QString("third");
}
}
return QVariant();
}
//! [quoting mymodel_c]

View File

@ -0,0 +1,21 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QAbstractTableModel>
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
};
#endif // MYMODEL_H

View File

@ -0,0 +1,17 @@
TARGET = mv_edit
TEMPLATE = app
QT += widgets
requires(qtConfig(tableview))
SOURCES += main.cpp \
mainwindow.cpp \
mymodel.cpp
HEADERS += mainwindow.h \
mymodel.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/5_edit
INSTALLS += target

View File

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

View File

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

View File

@ -0,0 +1,20 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "mainwindow.h"
#include "mymodel.h"
#include <QTableView>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, tableView(new QTableView(this))
{
setCentralWidget(tableView);
auto *myModel = new MyModel(this);
tableView->setModel(myModel);
// transfer changes to the model to the window title
connect(myModel, &MyModel::editCompleted,
this, &QWidget::setWindowTitle);
}

View File

@ -0,0 +1,24 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
class QTableView; // forward declaration
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
private:
QTableView *tableView;
};
#endif // MAINWINDOW_H

View File

@ -0,0 +1,60 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "mymodel.h"
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
//-----------------------------------------------------------------
int MyModel::rowCount(const QModelIndex & /*parent*/) const
{
return ROWS;
}
//-----------------------------------------------------------------
int MyModel::columnCount(const QModelIndex & /*parent*/) const
{
return COLS;
}
//-----------------------------------------------------------------
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole && checkIndex(index))
return m_gridData[index.row()][index.column()];
return QVariant();
}
//-----------------------------------------------------------------
//! [quoting mymodel_e]
bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role == Qt::EditRole) {
if (!checkIndex(index))
return false;
//save value from editor to member m_gridData
m_gridData[index.row()][index.column()] = value.toString();
//for presentation purposes only: build and emit a joined string
QString result;
for (int row = 0; row < ROWS; row++) {
for (int col= 0; col < COLS; col++)
result += m_gridData[row][col] + ' ';
}
emit editCompleted(result);
return true;
}
return false;
}
//! [quoting mymodel_e]
//-----------------------------------------------------------------
//! [quoting mymodel_f]
Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}
//! [quoting mymodel_f]

View File

@ -0,0 +1,33 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MYMODEL_H
#define MYMODEL_H
//! [Quoting ModelView Tutorial]
// mymodel.h
#include <QAbstractTableModel>
#include <QString>
const int COLS= 3;
const int ROWS= 2;
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
private:
QString m_gridData[ROWS][COLS]; //holds text entered into QTableView
signals:
void editCompleted(const QString &);
};
//! [Quoting ModelView Tutorial]
#endif // MYMODEL_H

View File

@ -0,0 +1,11 @@
TARGET = mv_tree
TEMPLATE = app
QT += widgets
requires(qtConfig(treeview))
SOURCES += main.cpp \
mainwindow.cpp
HEADERS += mainwindow.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/6_treeview
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(mv_tree LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/modelview/6_treeview")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(mv_tree
main.cpp
mainwindow.cpp mainwindow.h
)
set_target_properties(mv_tree PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(mv_tree PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS mv_tree
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

View File

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

View File

@ -0,0 +1,40 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
//! [Quoting ModelView Tutorial]
// modelview.cpp
#include "mainwindow.h"
#include <QTreeView>
#include <QStandardItemModel>
#include <QStandardItem>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, treeView(new QTreeView(this))
, standardModel(new QStandardItemModel(this))
{
setCentralWidget(treeView);
QList<QStandardItem *> preparedRow = prepareRow("first", "second", "third");
QStandardItem *item = standardModel->invisibleRootItem();
// adding a row to the invisible root item produces a root element
item->appendRow(preparedRow);
QList<QStandardItem *> secondRow = prepareRow("111", "222", "333");
// adding a row to an item starts a subtree
preparedRow.first()->appendRow(secondRow);
treeView->setModel(standardModel);
treeView->expandAll();
}
QList<QStandardItem *> MainWindow::prepareRow(const QString &first,
const QString &second,
const QString &third) const
{
return {new QStandardItem(first),
new QStandardItem(second),
new QStandardItem(third)};
}
//! [Quoting ModelView Tutorial]

View File

@ -0,0 +1,31 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
class QTreeView; // forward declarations
class QStandardItemModel;
class QStandardItem;
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
private:
QList<QStandardItem *> prepareRow(const QString &first,
const QString &second,
const QString &third) const;
QTreeView *treeView;
QStandardItemModel *standardModel;
};
#endif // MAINWINDOW_H

View File

@ -0,0 +1,11 @@
TARGET = mv_selections
TEMPLATE = app
QT += widgets
requires(qtConfig(treeview))
SOURCES += main.cpp \
mainwindow.cpp
HEADERS += mainwindow.h
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/modelview/7_selections
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(mv_selections LANGUAGES CXX)
if(NOT DEFINED INSTALL_EXAMPLESDIR)
set(INSTALL_EXAMPLESDIR "examples")
endif()
set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/widgets/tutorials/modelview/7_selections")
find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets)
qt_standard_project_setup()
qt_add_executable(mv_selections
main.cpp
mainwindow.cpp mainwindow.h
)
set_target_properties(mv_selections PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(mv_selections PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
)
install(TARGETS mv_selections
RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

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