C++/Qt/QDialog
Содержание
All standard dialog
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QLabel;
class QErrorMessage;
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
private slots:
void setInteger();
void setDouble();
void setItem();
void setText();
void setColor();
void setFont();
void setExistingDirectory();
void setOpenFileName();
void setOpenFileNames();
void setSaveFileName();
void criticalMessage();
void informationMessage();
void questionMessage();
void warningMessage();
void errorMessage();
private:
QCheckBox *native;
QLabel *integerLabel;
QLabel *doubleLabel;
QLabel *itemLabel;
QLabel *textLabel;
QLabel *colorLabel;
QLabel *fontLabel;
QLabel *directoryLabel;
QLabel *openFileNameLabel;
QLabel *openFileNamesLabel;
QLabel *saveFileNameLabel;
QLabel *criticalLabel;
QLabel *informationLabel;
QLabel *questionLabel;
QLabel *warningLabel;
QLabel *errorLabel;
QErrorMessage *errorMessageDialog;
QString openFilesPath;
};
#endif
#include <QtGui>
#include "dialog.h"
#define MESSAGE \
Dialog::tr("<p>Message boxes have a caption, a text, " \
"and any number of buttons, each with standard or custom texts." \
"<p>Click a button to close the message box. Pressing the Esc button " \
"will activate the detected escape button (if any).")
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
errorMessageDialog = new QErrorMessage(this);
int frameStyle = QFrame::Sunken | QFrame::Panel;
integerLabel = new QLabel;
integerLabel->setFrameStyle(frameStyle);
QPushButton *integerButton =
new QPushButton(tr("QInputDialog::get&Int()"));
doubleLabel = new QLabel;
doubleLabel->setFrameStyle(frameStyle);
QPushButton *doubleButton =
new QPushButton(tr("QInputDialog::get&Double()"));
itemLabel = new QLabel;
itemLabel->setFrameStyle(frameStyle);
QPushButton *itemButton = new QPushButton(tr("QInputDialog::getIte&m()"));
textLabel = new QLabel;
textLabel->setFrameStyle(frameStyle);
QPushButton *textButton = new QPushButton(tr("QInputDialog::get&Text()"));
colorLabel = new QLabel;
colorLabel->setFrameStyle(frameStyle);
QPushButton *colorButton = new QPushButton(tr("QColorDialog::get&Color()"));
fontLabel = new QLabel;
fontLabel->setFrameStyle(frameStyle);
QPushButton *fontButton = new QPushButton(tr("QFontDialog::get&Font()"));
directoryLabel = new QLabel;
directoryLabel->setFrameStyle(frameStyle);
QPushButton *directoryButton =
new QPushButton(tr("QFileDialog::getE&xistingDirectory()"));
openFileNameLabel = new QLabel;
openFileNameLabel->setFrameStyle(frameStyle);
QPushButton *openFileNameButton =
new QPushButton(tr("QFileDialog::get&OpenFileName()"));
openFileNamesLabel = new QLabel;
openFileNamesLabel->setFrameStyle(frameStyle);
QPushButton *openFileNamesButton =
new QPushButton(tr("QFileDialog::&getOpenFileNames()"));
saveFileNameLabel = new QLabel;
saveFileNameLabel->setFrameStyle(frameStyle);
QPushButton *saveFileNameButton =
new QPushButton(tr("QFileDialog::get&SaveFileName()"));
criticalLabel = new QLabel;
criticalLabel->setFrameStyle(frameStyle);
QPushButton *criticalButton =
new QPushButton(tr("QMessageBox::critica&l()"));
informationLabel = new QLabel;
informationLabel->setFrameStyle(frameStyle);
QPushButton *informationButton =
new QPushButton(tr("QMessageBox::i&nformation()"));
questionLabel = new QLabel;
questionLabel->setFrameStyle(frameStyle);
QPushButton *questionButton =
new QPushButton(tr("QMessageBox::&question()"));
warningLabel = new QLabel;
warningLabel->setFrameStyle(frameStyle);
QPushButton *warningButton = new QPushButton(tr("QMessageBox::&warning()"));
errorLabel = new QLabel;
errorLabel->setFrameStyle(frameStyle);
QPushButton *errorButton =
new QPushButton(tr("QErrorMessage::show&M&essage()"));
connect(integerButton, SIGNAL(clicked()), this, SLOT(setInteger()));
connect(doubleButton, SIGNAL(clicked()), this, SLOT(setDouble()));
connect(itemButton, SIGNAL(clicked()), this, SLOT(setItem()));
connect(textButton, SIGNAL(clicked()), this, SLOT(setText()));
connect(colorButton, SIGNAL(clicked()), this, SLOT(setColor()));
connect(fontButton, SIGNAL(clicked()), this, SLOT(setFont()));
connect(directoryButton, SIGNAL(clicked()),
this, SLOT(setExistingDirectory()));
connect(openFileNameButton, SIGNAL(clicked()),
this, SLOT(setOpenFileName()));
connect(openFileNamesButton, SIGNAL(clicked()),
this, SLOT(setOpenFileNames()));
connect(saveFileNameButton, SIGNAL(clicked()),
this, SLOT(setSaveFileName()));
connect(criticalButton, SIGNAL(clicked()), this, SLOT(criticalMessage()));
connect(informationButton, SIGNAL(clicked()),
this, SLOT(informationMessage()));
connect(questionButton, SIGNAL(clicked()), this, SLOT(questionMessage()));
connect(warningButton, SIGNAL(clicked()), this, SLOT(warningMessage()));
connect(errorButton, SIGNAL(clicked()), this, SLOT(errorMessage()));
native = new QCheckBox(this);
native->setText("Use native file dialog.");
native->setChecked(true);
#ifndef Q_WS_WIN
#ifndef Q_OS_MAC
native->hide();
#endif
#endif
QGridLayout *layout = new QGridLayout;
layout->setColumnStretch(1, 1);
layout->setColumnMinimumWidth(1, 250);
layout->addWidget(integerButton, 0, 0);
layout->addWidget(integerLabel, 0, 1);
layout->addWidget(doubleButton, 1, 0);
layout->addWidget(doubleLabel, 1, 1);
layout->addWidget(itemButton, 2, 0);
layout->addWidget(itemLabel, 2, 1);
layout->addWidget(textButton, 3, 0);
layout->addWidget(textLabel, 3, 1);
layout->addWidget(colorButton, 4, 0);
layout->addWidget(colorLabel, 4, 1);
layout->addWidget(fontButton, 5, 0);
layout->addWidget(fontLabel, 5, 1);
layout->addWidget(directoryButton, 6, 0);
layout->addWidget(directoryLabel, 6, 1);
layout->addWidget(openFileNameButton, 7, 0);
layout->addWidget(openFileNameLabel, 7, 1);
layout->addWidget(openFileNamesButton, 8, 0);
layout->addWidget(openFileNamesLabel, 8, 1);
layout->addWidget(saveFileNameButton, 9, 0);
layout->addWidget(saveFileNameLabel, 9, 1);
layout->addWidget(criticalButton, 10, 0);
layout->addWidget(criticalLabel, 10, 1);
layout->addWidget(informationButton, 11, 0);
layout->addWidget(informationLabel, 11, 1);
layout->addWidget(questionButton, 12, 0);
layout->addWidget(questionLabel, 12, 1);
layout->addWidget(warningButton, 13, 0);
layout->addWidget(warningLabel, 13, 1);
layout->addWidget(errorButton, 14, 0);
layout->addWidget(errorLabel, 14, 1);
layout->addWidget(native, 15, 0);
setLayout(layout);
setWindowTitle(tr("Standard Dialogs"));
}
void Dialog::setInteger()
{
bool ok;
int i = QInputDialog::getInt(this, tr("QInputDialog::getInteger()"),
tr("Percentage:"), 25, 0, 100, 1, &ok);
if (ok)
integerLabel->setText(tr("%1%").arg(i));
}
void Dialog::setDouble()
{
bool ok;
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
tr("Amount:"), 37.56, -10000, 10000, 2, &ok);
if (ok)
doubleLabel->setText(QString("$%1").arg(d));
}
void Dialog::setItem()
{
QStringList items;
items << tr("Spring") << tr("Summer") << tr("Fall") << tr("Winter");
bool ok;
QString item = QInputDialog::getItem(this, tr("QInputDialog::getItem()"),
tr("Season:"), items, 0, false, &ok);
if (ok && !item.isEmpty())
itemLabel->setText(item);
}
void Dialog::setText()
{
bool ok;
QString text = QInputDialog::getText(this, tr("QInputDialog::getText()"),
tr("User name:"), QLineEdit::Normal,
QDir::home().dirName(), &ok);
if (ok && !text.isEmpty())
textLabel->setText(text);
}
void Dialog::setColor()
{
QColor color = QColorDialog::getColor(Qt::green, this);
if (color.isValid()) {
colorLabel->setText(color.name());
colorLabel->setPalette(QPalette(color));
colorLabel->setAutoFillBackground(true);
}
}
void Dialog::setFont()
{
bool ok;
QFont font = QFontDialog::getFont(&ok, QFont(fontLabel->text()), this);
if (ok) {
fontLabel->setText(font.key());
fontLabel->setFont(font);
}
}
void Dialog::setExistingDirectory()
{
QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly;
if (!native->isChecked())
options |= QFileDialog::DontUseNativeDialog;
QString directory = QFileDialog::getExistingDirectory(this,
tr("QFileDialog::getExistingDirectory()"),
directoryLabel->text(),
options);
if (!directory.isEmpty())
directoryLabel->setText(directory);
}
void Dialog::setOpenFileName()
{
QFileDialog::Options options;
if (!native->isChecked())
options |= QFileDialog::DontUseNativeDialog;
QString selectedFilter;
QString fileName = QFileDialog::getOpenFileName(this,
tr("QFileDialog::getOpenFileName()"),
openFileNameLabel->text(),
tr("All Files (*);;Text Files (*.txt)"),
&selectedFilter,
options);
if (!fileName.isEmpty())
openFileNameLabel->setText(fileName);
}
void Dialog::setOpenFileNames()
{
QFileDialog::Options options;
if (!native->isChecked())
options |= QFileDialog::DontUseNativeDialog;
QString selectedFilter;
QStringList files = QFileDialog::getOpenFileNames(
this, tr("QFileDialog::getOpenFileNames()"),
openFilesPath,
tr("All Files (*);;Text Files (*.txt)"),
&selectedFilter,
options);
if (files.count()) {
openFilesPath = files[0];
openFileNamesLabel->setText(QString("[%1]").arg(files.join(", ")));
}
}
void Dialog::setSaveFileName()
{
QFileDialog::Options options;
if (!native->isChecked())
options |= QFileDialog::DontUseNativeDialog;
QString selectedFilter;
QString fileName = QFileDialog::getSaveFileName(this,
tr("QFileDialog::getSaveFileName()"),
saveFileNameLabel->text(),
tr("All Files (*);;Text Files (*.txt)"),
&selectedFilter,
options);
if (!fileName.isEmpty())
saveFileNameLabel->setText(fileName);
}
void Dialog::criticalMessage()
{
QMessageBox::StandardButton reply;
reply = QMessageBox::critical(this, tr("QMessageBox::critical()"),
MESSAGE,
QMessageBox::Abort | QMessageBox::Retry | QMessageBox::Ignore);
if (reply == QMessageBox::Abort)
criticalLabel->setText(tr("Abort"));
else if (reply == QMessageBox::Retry)
criticalLabel->setText(tr("Retry"));
else
criticalLabel->setText(tr("Ignore"));
}
void Dialog::informationMessage()
{
QMessageBox::StandardButton reply;
reply = QMessageBox::information(this, tr("QMessageBox::information()"), MESSAGE);
if (reply == QMessageBox::Ok)
informationLabel->setText(tr("OK"));
else
informationLabel->setText(tr("Escape"));
}
void Dialog::questionMessage()
{
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("QMessageBox::question()"),
MESSAGE,
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
if (reply == QMessageBox::Yes)
questionLabel->setText(tr("Yes"));
else if (reply == QMessageBox::No)
questionLabel->setText(tr("No"));
else
questionLabel->setText(tr("Cancel"));
}
void Dialog::warningMessage()
{
QMessageBox msgBox(QMessageBox::Warning, tr("QMessageBox::warning()"),
MESSAGE, 0, this);
msgBox.addButton(tr("Save &Again"), QMessageBox::AcceptRole);
msgBox.addButton(tr("&Continue"), QMessageBox::RejectRole);
if (msgBox.exec() == QMessageBox::AcceptRole)
warningLabel->setText(tr("Save Again"));
else
warningLabel->setText(tr("Continue"));
}
void Dialog::errorMessage()
{
errorMessageDialog->showMessage(
tr("This dialog shows and remembers error messages. "
"If the checkbox is checked (as it is by default), "
"the shown message will be shown again, "
"but if the user unchecks the box the message "
"will not appear again if QErrorMessage::showMessage() "
"is called with the same message."));
errorLabel->setText(tr("If the box is unchecked, the message "
"won"t appear again."));
}
#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>
#include "dialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QString translatorFileName = QLatin1String("qt_");
translatorFileName += QLocale::system().name();
QTranslator *translator = new QTranslator(&app);
if (translator->load(translatorFileName, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(translator);
Dialog dialog;
return dialog.exec();
}
Config dialog
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef CONFIGDIALOG_H
#define CONFIGDIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
class QListWidget;
class QListWidgetItem;
class QStackedWidget;
QT_END_NAMESPACE
class ConfigDialog : public QDialog
{
Q_OBJECT
public:
ConfigDialog();
public slots:
void changePage(QListWidgetItem *current, QListWidgetItem *previous);
private:
void createIcons();
QListWidget *contentsWidget;
QStackedWidget *pagesWidget;
};
#endif
#include <QtGui>
#include "configdialog.h"
#include "pages.h"
ConfigDialog::ConfigDialog()
{
contentsWidget = new QListWidget;
contentsWidget->setViewMode(QListView::IconMode);
contentsWidget->setIconSize(QSize(96, 84));
contentsWidget->setMovement(QListView::Static);
contentsWidget->setMaximumWidth(128);
contentsWidget->setSpacing(12);
pagesWidget = new QStackedWidget;
pagesWidget->addWidget(new ConfigurationPage);
pagesWidget->addWidget(new UpdatePage);
pagesWidget->addWidget(new QueryPage);
QPushButton *closeButton = new QPushButton(tr("Close"));
createIcons();
contentsWidget->setCurrentRow(0);
connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
QHBoxLayout *horizontalLayout = new QHBoxLayout;
horizontalLayout->addWidget(contentsWidget);
horizontalLayout->addWidget(pagesWidget, 1);
QHBoxLayout *buttonsLayout = new QHBoxLayout;
buttonsLayout->addStretch(1);
buttonsLayout->addWidget(closeButton);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(horizontalLayout);
mainLayout->addStretch(1);
mainLayout->addSpacing(12);
mainLayout->addLayout(buttonsLayout);
setLayout(mainLayout);
setWindowTitle(tr("Config Dialog"));
}
void ConfigDialog::createIcons()
{
QListWidgetItem *configButton = new QListWidgetItem(contentsWidget);
configButton->setIcon(QIcon(":/images/config.png"));
configButton->setText(tr("Configuration"));
configButton->setTextAlignment(Qt::AlignHCenter);
configButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
QListWidgetItem *updateButton = new QListWidgetItem(contentsWidget);
updateButton->setIcon(QIcon(":/images/update.png"));
updateButton->setText(tr("Update"));
updateButton->setTextAlignment(Qt::AlignHCenter);
updateButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
QListWidgetItem *queryButton = new QListWidgetItem(contentsWidget);
queryButton->setIcon(QIcon(":/images/query.png"));
queryButton->setText(tr("Query"));
queryButton->setTextAlignment(Qt::AlignHCenter);
queryButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
connect(contentsWidget,
SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)),
this, SLOT(changePage(QListWidgetItem *, QListWidgetItem*)));
}
void ConfigDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous)
{
if (!current)
current = previous;
pagesWidget->setCurrentIndex(contentsWidget->row(current));
}
#ifndef PAGES_H
#define PAGES_H
#include <QWidget>
class ConfigurationPage : public QWidget
{
public:
ConfigurationPage(QWidget *parent = 0);
};
class QueryPage : public QWidget
{
public:
QueryPage(QWidget *parent = 0);
};
class UpdatePage : public QWidget
{
public:
UpdatePage(QWidget *parent = 0);
};
#endif
#include <QtGui>
#include "pages.h"
ConfigurationPage::ConfigurationPage(QWidget *parent)
: QWidget(parent)
{
QGroupBox *configGroup = new QGroupBox(tr("Server configuration"));
QLabel *serverLabel = new QLabel(tr("Server:"));
QComboBox *serverCombo = new QComboBox;
serverCombo->addItem(tr("Qt (Australia)"));
serverCombo->addItem(tr("Qt (Germany)"));
serverCombo->addItem(tr("Qt (Norway)"));
serverCombo->addItem(tr("Qt (People"s Republic of China)"));
serverCombo->addItem(tr("Qt (USA)"));
QHBoxLayout *serverLayout = new QHBoxLayout;
serverLayout->addWidget(serverLabel);
serverLayout->addWidget(serverCombo);
QVBoxLayout *configLayout = new QVBoxLayout;
configLayout->addLayout(serverLayout);
configGroup->setLayout(configLayout);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(configGroup);
mainLayout->addStretch(1);
setLayout(mainLayout);
}
UpdatePage::UpdatePage(QWidget *parent)
: QWidget(parent)
{
QGroupBox *updateGroup = new QGroupBox(tr("Package selection"));
QCheckBox *systemCheckBox = new QCheckBox(tr("Update system"));
QCheckBox *appsCheckBox = new QCheckBox(tr("Update applications"));
QCheckBox *docsCheckBox = new QCheckBox(tr("Update documentation"));
QGroupBox *packageGroup = new QGroupBox(tr("Existing packages"));
QListWidget *packageList = new QListWidget;
QListWidgetItem *qtItem = new QListWidgetItem(packageList);
qtItem->setText(tr("Qt"));
QListWidgetItem *qsaItem = new QListWidgetItem(packageList);
qsaItem->setText(tr("QSA"));
QListWidgetItem *teamBuilderItem = new QListWidgetItem(packageList);
teamBuilderItem->setText(tr("Teambuilder"));
QPushButton *startUpdateButton = new QPushButton(tr("Start update"));
QVBoxLayout *updateLayout = new QVBoxLayout;
updateLayout->addWidget(systemCheckBox);
updateLayout->addWidget(appsCheckBox);
updateLayout->addWidget(docsCheckBox);
updateGroup->setLayout(updateLayout);
QVBoxLayout *packageLayout = new QVBoxLayout;
packageLayout->addWidget(packageList);
packageGroup->setLayout(packageLayout);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(updateGroup);
mainLayout->addWidget(packageGroup);
mainLayout->addSpacing(12);
mainLayout->addWidget(startUpdateButton);
mainLayout->addStretch(1);
setLayout(mainLayout);
}
QueryPage::QueryPage(QWidget *parent)
: QWidget(parent)
{
QGroupBox *packagesGroup = new QGroupBox(tr("Look for packages"));
QLabel *nameLabel = new QLabel(tr("Name:"));
QLineEdit *nameEdit = new QLineEdit;
QLabel *dateLabel = new QLabel(tr("Released after:"));
QDateTimeEdit *dateEdit = new QDateTimeEdit(QDate::currentDate());
QCheckBox *releasesCheckBox = new QCheckBox(tr("Releases"));
QCheckBox *upgradesCheckBox = new QCheckBox(tr("Upgrades"));
QSpinBox *hitsSpinBox = new QSpinBox;
hitsSpinBox->setPrefix(tr("Return up to "));
hitsSpinBox->setSuffix(tr(" results"));
hitsSpinBox->setSpecialValueText(tr("Return only the first result"));
hitsSpinBox->setMinimum(1);
hitsSpinBox->setMaximum(100);
hitsSpinBox->setSingleStep(10);
QPushButton *startQueryButton = new QPushButton(tr("Start query"));
QGridLayout *packagesLayout = new QGridLayout;
packagesLayout->addWidget(nameLabel, 0, 0);
packagesLayout->addWidget(nameEdit, 0, 1);
packagesLayout->addWidget(dateLabel, 1, 0);
packagesLayout->addWidget(dateEdit, 1, 1);
packagesLayout->addWidget(releasesCheckBox, 2, 0);
packagesLayout->addWidget(upgradesCheckBox, 3, 0);
packagesLayout->addWidget(hitsSpinBox, 4, 0, 1, 2);
packagesGroup->setLayout(packagesLayout);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(packagesGroup);
mainLayout->addSpacing(12);
mainLayout->addWidget(startQueryButton);
mainLayout->addStretch(1);
setLayout(mainLayout);
}
#include <QApplication>
#include "configdialog.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(configdialog);
QApplication app(argc, argv);
ConfigDialog dialog;
return dialog.exec();
}
extends QDialog
Chapter03\buttonbox\buttonbox.cpp
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "ButtonBox.h"
#include <QPushButton>
#include <QDialogButtonBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QMessageBox>
ButtonBoxDialog::ButtonBoxDialog() : QDialog(0)
{
QVBoxLayout *layout = new QVBoxLayout( this );
QPushButton *button;
QDialogButtonBox *box = new QDialogButtonBox( Qt::Horizontal );
button = new QPushButton( "Ok" );
connect( button, SIGNAL(clicked()), this, SLOT(okClicked()) );
box->addButton( button, QDialogButtonBox::AcceptRole );
button = new QPushButton( "Cancel" );
connect( button, SIGNAL(clicked()), this, SLOT(cancelClicked()) );
box->addButton( button, QDialogButtonBox::RejectRole );
button = new QPushButton( "Apply" );
connect( button, SIGNAL(clicked()), this, SLOT(applyClicked()) );
box->addButton( button, QDialogButtonBox::ApplyRole );
button = new QPushButton( "Reset" );
connect( button, SIGNAL(clicked()), this, SLOT(resetClicked()) );
box->addButton( button, QDialogButtonBox::ResetRole );
button = new QPushButton( "Help" );
connect( button, SIGNAL(clicked()), this, SLOT(helpClicked()) );
box->addButton( button, QDialogButtonBox::HelpRole );
layout->addWidget( new QLabel( "Try out the buttons!" ) );
layout->addWidget( box );
}
void ButtonBoxDialog::okClicked()
{
QMessageBox::information( this, "Demo", "Ok Clicked" );
}
void ButtonBoxDialog::cancelClicked()
{
QMessageBox::information( this, "Demo", "Cancel Clicked" );
}
void ButtonBoxDialog::applyClicked()
{
QMessageBox::information( this, "Demo", "Apply Clicked" );
}
void ButtonBoxDialog::resetClicked()
{
QMessageBox::information( this, "Demo", "Reset Clicked" );
}
void ButtonBoxDialog::helpClicked()
{
QMessageBox::information( this, "Demo", "Help Clicked" );
}
Chapter03\buttonbox\buttonbox.h
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef BUTTONBOX_H
#define BUTTONBOX_H
#include <QDialog>
class ButtonBoxDialog : public QDialog
{
Q_OBJECT
public:
ButtonBoxDialog();
public slots:
void okClicked();
void cancelClicked();
void applyClicked();
void resetClicked();
void helpClicked();
};
#endif // BUTTONBOX_H
Chapter03\buttonbox\main.cpp
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QApplication>
#include <QCleanlooksStyle>
#include "buttonbox.h"
int main( int argc, char **argv )
{
QApplication app( argc, argv );
app.setStyle( new QCleanlooksStyle );
ButtonBoxDialog dlg;
dlg.show();
return app.exec();
}
Find dialog
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QDialogButtonBox;
class QGroupBox;
class QLabel;
class QLineEdit;
class QPushButton;
QT_END_NAMESPACE
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = 0);
private:
QLabel *label;
QLineEdit *lineEdit;
QCheckBox *caseCheckBox;
QCheckBox *fromStartCheckBox;
QCheckBox *wholeWordsCheckBox;
QCheckBox *searchSelectionCheckBox;
QCheckBox *backwardCheckBox;
QDialogButtonBox *buttonBox;
QPushButton *findButton;
QPushButton *moreButton;
QWidget *extension;
};
#endif
#include <QtGui>
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);
caseCheckBox = new QCheckBox(tr("Match &case"));
fromStartCheckBox = new QCheckBox(tr("Search from &start"));
fromStartCheckBox->setChecked(true);
findButton = new QPushButton(tr("&Find"));
findButton->setDefault(true);
moreButton = new QPushButton(tr("&More"));
moreButton->setCheckable(true);
moreButton->setAutoDefault(false);
buttonBox = new QDialogButtonBox(Qt::Vertical);
buttonBox->addButton(findButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(moreButton, QDialogButtonBox::ActionRole);
extension = new QWidget;
wholeWordsCheckBox = new QCheckBox(tr("&Whole words"));
backwardCheckBox = new QCheckBox(tr("Search &backward"));
searchSelectionCheckBox = new QCheckBox(tr("Search se&lection"));
connect(moreButton, SIGNAL(toggled(bool)), extension, SLOT(setVisible(bool)));
QVBoxLayout *extensionLayout = new QVBoxLayout;
extensionLayout->setMargin(0);
extensionLayout->addWidget(wholeWordsCheckBox);
extensionLayout->addWidget(backwardCheckBox);
extensionLayout->addWidget(searchSelectionCheckBox);
extension->setLayout(extensionLayout);
QHBoxLayout *topLeftLayout = new QHBoxLayout;
topLeftLayout->addWidget(label);
topLeftLayout->addWidget(lineEdit);
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout(topLeftLayout);
leftLayout->addWidget(caseCheckBox);
leftLayout->addWidget(fromStartCheckBox);
leftLayout->addStretch(1);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
mainLayout->addLayout(leftLayout, 0, 0);
mainLayout->addWidget(buttonBox, 0, 1);
mainLayout->addWidget(extension, 1, 0, 1, 2);
setLayout(mainLayout);
setWindowTitle(tr("Extension"));
extension->hide();
}
#include <QApplication>
#include "finddialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
FindDialog dialog;
return dialog.exec();
}
Find file dialog
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef WINDOW_H
#define WINDOW_H
#include <QDialog>
#include <QDir>
QT_BEGIN_NAMESPACE
class QComboBox;
class QLabel;
class QPushButton;
class QTableWidget;
class QTableWidgetItem;
QT_END_NAMESPACE
class Window : public QDialog
{
Q_OBJECT
public:
Window(QWidget *parent = 0);
private slots:
void browse();
void find();
void openFileOfItem(int row, int column);
private:
QStringList findFiles(const QStringList &files, const QString &text);
void showFiles(const QStringList &files);
QPushButton *createButton(const QString &text, const char *member);
QComboBox *createComboBox(const QString &text = QString());
void createFilesTable();
QComboBox *fileComboBox;
QComboBox *textComboBox;
QComboBox *directoryComboBox;
QLabel *fileLabel;
QLabel *textLabel;
QLabel *directoryLabel;
QLabel *filesFoundLabel;
QPushButton *browseButton;
QPushButton *findButton;
QTableWidget *filesTable;
QDir currentDir;
};
#endif
#include <QtGui>
#include "window.h"
Window::Window(QWidget *parent)
: QDialog(parent)
{
browseButton = createButton(tr("&Browse..."), SLOT(browse()));
findButton = createButton(tr("&Find"), SLOT(find()));
fileComboBox = createComboBox(tr("*"));
textComboBox = createComboBox();
directoryComboBox = createComboBox(QDir::currentPath());
fileLabel = new QLabel(tr("Named:"));
textLabel = new QLabel(tr("Containing text:"));
directoryLabel = new QLabel(tr("In directory:"));
filesFoundLabel = new QLabel;
createFilesTable();
QHBoxLayout *buttonsLayout = new QHBoxLayout;
buttonsLayout->addStretch();
buttonsLayout->addWidget(findButton);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(fileLabel, 0, 0);
mainLayout->addWidget(fileComboBox, 0, 1, 1, 2);
mainLayout->addWidget(textLabel, 1, 0);
mainLayout->addWidget(textComboBox, 1, 1, 1, 2);
mainLayout->addWidget(directoryLabel, 2, 0);
mainLayout->addWidget(directoryComboBox, 2, 1);
mainLayout->addWidget(browseButton, 2, 2);
mainLayout->addWidget(filesTable, 3, 0, 1, 3);
mainLayout->addWidget(filesFoundLabel, 4, 0);
mainLayout->addLayout(buttonsLayout, 5, 0, 1, 3);
setLayout(mainLayout);
setWindowTitle(tr("Find Files"));
resize(700, 300);
}
void Window::browse()
{
QString directory = QFileDialog::getExistingDirectory(this,
tr("Find Files"), QDir::currentPath());
if (!directory.isEmpty()) {
if (directoryComboBox->findText(directory) == -1)
directoryComboBox->addItem(directory);
directoryComboBox->setCurrentIndex(directoryComboBox->findText(directory));
}
}
static void updateComboBox(QComboBox *comboBox)
{
if (comboBox->findText(comboBox->currentText()) == -1)
comboBox->addItem(comboBox->currentText());
}
void Window::find()
{
filesTable->setRowCount(0);
QString fileName = fileComboBox->currentText();
QString text = textComboBox->currentText();
QString path = directoryComboBox->currentText();
updateComboBox(fileComboBox);
updateComboBox(textComboBox);
updateComboBox(directoryComboBox);
currentDir = QDir(path);
QStringList files;
if (fileName.isEmpty())
fileName = "*";
files = currentDir.entryList(QStringList(fileName),
QDir::Files | QDir::NoSymLinks);
if (!text.isEmpty())
files = findFiles(files, text);
showFiles(files);
}
QStringList Window::findFiles(const QStringList &files, const QString &text)
{
QProgressDialog progressDialog(this);
progressDialog.setCancelButtonText(tr("&Cancel"));
progressDialog.setRange(0, files.size());
progressDialog.setWindowTitle(tr("Find Files"));
QStringList foundFiles;
for (int i = 0; i < files.size(); ++i) {
progressDialog.setValue(i);
progressDialog.setLabelText(tr("Searching file number %1 of %2...")
.arg(i).arg(files.size()));
qApp->processEvents();
if (progressDialog.wasCanceled())
break;
QFile file(currentDir.absoluteFilePath(files[i]));
if (file.open(QIODevice::ReadOnly)) {
QString line;
QTextStream in(&file);
while (!in.atEnd()) {
if (progressDialog.wasCanceled())
break;
line = in.readLine();
if (line.contains(text)) {
foundFiles << files[i];
break;
}
}
}
}
return foundFiles;
}
void Window::showFiles(const QStringList &files)
{
for (int i = 0; i < files.size(); ++i) {
QFile file(currentDir.absoluteFilePath(files[i]));
qint64 size = QFileInfo(file).size();
QTableWidgetItem *fileNameItem = new QTableWidgetItem(files[i]);
fileNameItem->setFlags(fileNameItem->flags() ^ Qt::ItemIsEditable);
QTableWidgetItem *sizeItem = new QTableWidgetItem(tr("%1 KB")
.arg(int((size + 1023) / 1024)));
sizeItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);
int row = filesTable->rowCount();
filesTable->insertRow(row);
filesTable->setItem(row, 0, fileNameItem);
filesTable->setItem(row, 1, sizeItem);
}
filesFoundLabel->setText(tr("%1 file(s) found").arg(files.size()) +
(" (Double click on a file to open it)"));
}
QPushButton *Window::createButton(const QString &text, const char *member)
{
QPushButton *button = new QPushButton(text);
connect(button, SIGNAL(clicked()), this, member);
return button;
}
QComboBox *Window::createComboBox(const QString &text)
{
QComboBox *comboBox = new QComboBox;
comboBox->setEditable(true);
comboBox->addItem(text);
comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
return comboBox;
}
void Window::createFilesTable()
{
filesTable = new QTableWidget(0, 2);
filesTable->setSelectionBehavior(QAbstractItemView::SelectRows);
QStringList labels;
labels << tr("File Name") << tr("Size");
filesTable->setHorizontalHeaderLabels(labels);
filesTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
filesTable->verticalHeader()->hide();
filesTable->setShowGrid(false);
connect(filesTable, SIGNAL(cellActivated(int, int)),
this, SLOT(openFileOfItem(int, int)));
}
void Window::openFileOfItem(int row, int /* column */)
{
QTableWidgetItem *item = filesTable->item(row, 0);
QDesktopServices::openUrl(currentDir.absoluteFilePath(item->text()));
}
#include <QApplication>
#include "window.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Window window;
window.show();
return app.exec();
}
Order information dialog
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef DETAILSDIALOG_H
#define DETAILSDIALOG_H
#include <QDialog>
#include <QList>
#include <QPair>
#include <QString>
QT_BEGIN_NAMESPACE
class QCheckBox;
class QDialogButtonBox;
class QLabel;
class QLineEdit;
class QTableWidget;
class QTextEdit;
class QWidget;
QT_END_NAMESPACE
class DetailsDialog : public QDialog
{
Q_OBJECT
public:
DetailsDialog(const QString &title, QWidget *parent);
public slots:
void verify();
public:
QList<QPair<QString, int> > orderItems();
QString senderName() const;
QString senderAddress() const;
bool sendOffers();
private:
void setupItemsTable();
QLabel *nameLabel;
QLabel *addressLabel;
QCheckBox *offersCheckBox;
QLineEdit *nameEdit;
QStringList items;
QTableWidget *itemsTable;
QTextEdit *addressEdit;
QDialogButtonBox *buttonBox;
};
#endif
#include <QtGui>
#include "detailsdialog.h"
DetailsDialog::DetailsDialog(const QString &title, QWidget *parent)
: QDialog(parent)
{
nameLabel = new QLabel(tr("Name:"));
addressLabel = new QLabel(tr("Address:"));
addressLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
nameEdit = new QLineEdit;
addressEdit = new QTextEdit;
offersCheckBox = new QCheckBox(tr("Send information about products and "
"special offers"));
setupItemsTable();
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
| QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(verify()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameEdit, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0);
mainLayout->addWidget(addressEdit, 1, 1);
mainLayout->addWidget(itemsTable, 0, 2, 2, 1);
mainLayout->addWidget(offersCheckBox, 2, 1, 1, 2);
mainLayout->addWidget(buttonBox, 3, 0, 1, 3);
setLayout(mainLayout);
setWindowTitle(title);
}
void DetailsDialog::setupItemsTable()
{
items << tr("T-shirt") << tr("Badge") << tr("Reference book")
<< tr("Coffee cup");
itemsTable = new QTableWidget(items.count(), 2);
for (int row = 0; row < items.count(); ++row) {
QTableWidgetItem *name = new QTableWidgetItem(items[row]);
name->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
itemsTable->setItem(row, 0, name);
QTableWidgetItem *quantity = new QTableWidgetItem("1");
itemsTable->setItem(row, 1, quantity);
}
}
QList<QPair<QString, int> > DetailsDialog::orderItems()
{
QList<QPair<QString, int> > orderList;
for (int row = 0; row < items.count(); ++row) {
QPair<QString, int> item;
item.first = itemsTable->item(row, 0)->text();
int quantity = itemsTable->item(row, 1)->data(Qt::DisplayRole).toInt();
item.second = qMax(0, quantity);
orderList.append(item);
}
return orderList;
}
QString DetailsDialog::senderName() const
{
return nameEdit->text();
}
QString DetailsDialog::senderAddress() const
{
return addressEdit->toPlainText();
}
bool DetailsDialog::sendOffers()
{
return offersCheckBox->isChecked();
}
void DetailsDialog::verify()
{
if (!nameEdit->text().isEmpty() && !addressEdit->toPlainText().isEmpty()) {
accept();
return;
}
QMessageBox::StandardButton answer;
answer = QMessageBox::warning(this, tr("Incomplete Form"),
tr("The form does not contain all the necessary information.\n"
"Do you want to discard it?"),
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes)
reject();
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QList>
#include <QMainWindow>
#include <QPair>
QT_BEGIN_NAMESPACE
class QAction;
class QTabWidget;
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
void createSample();
public slots:
void openDialog();
void printFile();
private:
void createLetter(const QString &name, const QString &address,
QList<QPair<QString,int> > orderItems,
bool sendOffers);
QAction *printAction;
QTabWidget *letters;
};
#endif
#include <QtGui>
#include "detailsdialog.h"
#include "mainwindow.h"
MainWindow::MainWindow()
{
QMenu *fileMenu = new QMenu(tr("&File"), this);
QAction *newAction = fileMenu->addAction(tr("&New..."));
newAction->setShortcut(tr("Ctrl+N"));
printAction = fileMenu->addAction(tr("&Print..."), this, SLOT(printFile()));
printAction->setShortcut(tr("Ctrl+P"));
printAction->setEnabled(false);
QAction *quitAction = fileMenu->addAction(tr("E&xit"));
quitAction->setShortcut(tr("Ctrl+Q"));
menuBar()->addMenu(fileMenu);
letters = new QTabWidget;
connect(newAction, SIGNAL(triggered()), this, SLOT(openDialog()));
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
setCentralWidget(letters);
setWindowTitle(tr("Order Form"));
}
void MainWindow::createLetter(const QString &name, const QString &address,
QList<QPair<QString,int> > orderItems,
bool sendOffers)
{
QTextEdit *editor = new QTextEdit;
int tabIndex = letters->addTab(editor, name);
letters->setCurrentIndex(tabIndex);
QTextCursor cursor(editor->textCursor());
cursor.movePosition(QTextCursor::Start);
QTextFrame *topFrame = cursor.currentFrame();
QTextFrameFormat topFrameFormat = topFrame->frameFormat();
topFrameFormat.setPadding(16);
topFrame->setFrameFormat(topFrameFormat);
QTextCharFormat textFormat;
QTextCharFormat boldFormat;
boldFormat.setFontWeight(QFont::Bold);
QTextFrameFormat referenceFrameFormat;
referenceFrameFormat.setBorder(1);
referenceFrameFormat.setPadding(8);
referenceFrameFormat.setPosition(QTextFrameFormat::FloatRight);
referenceFrameFormat.setWidth(QTextLength(QTextLength::PercentageLength, 40));
cursor.insertFrame(referenceFrameFormat);
cursor.insertText("A company", boldFormat);
cursor.insertBlock();
cursor.insertText("321 City Street");
cursor.insertBlock();
cursor.insertText("Industry Park");
cursor.insertBlock();
cursor.insertText("Another country");
cursor.setPosition(topFrame->lastPosition());
cursor.insertText(name, textFormat);
QString line;
foreach (line, address.split("\n")) {
cursor.insertBlock();
cursor.insertText(line);
}
cursor.insertBlock();
cursor.insertBlock();
QDate date = QDate::currentDate();
cursor.insertText(tr("Date: %1").arg(date.toString("d MMMM yyyy")),
textFormat);
cursor.insertBlock();
QTextFrameFormat bodyFrameFormat;
bodyFrameFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100));
cursor.insertFrame(bodyFrameFormat);
cursor.insertText(tr("I would like to place an order for the following "
"items:"), textFormat);
cursor.insertBlock();
cursor.insertBlock();
QTextTableFormat orderTableFormat;
orderTableFormat.setAlignment(Qt::AlignHCenter);
QTextTable *orderTable = cursor.insertTable(1, 2, orderTableFormat);
QTextFrameFormat orderFrameFormat = cursor.currentFrame()->frameFormat();
orderFrameFormat.setBorder(1);
cursor.currentFrame()->setFrameFormat(orderFrameFormat);
cursor = orderTable->cellAt(0, 0).firstCursorPosition();
cursor.insertText(tr("Product"), boldFormat);
cursor = orderTable->cellAt(0, 1).firstCursorPosition();
cursor.insertText(tr("Quantity"), boldFormat);
for (int i = 0; i < orderItems.count(); ++i) {
QPair<QString,int> item = orderItems[i];
int row = orderTable->rows();
orderTable->insertRows(row, 1);
cursor = orderTable->cellAt(row, 0).firstCursorPosition();
cursor.insertText(item.first, textFormat);
cursor = orderTable->cellAt(row, 1).firstCursorPosition();
cursor.insertText(QString("%1").arg(item.second), textFormat);
}
cursor.setPosition(topFrame->lastPosition());
cursor.insertBlock();
cursor.insertText(tr("Please update my records to take account of the "
"following privacy information:"));
cursor.insertBlock();
QTextTable *offersTable = cursor.insertTable(2, 2);
cursor = offersTable->cellAt(0, 1).firstCursorPosition();
cursor.insertText(tr("I want to receive more information about your "
"company"s products and special offers."), textFormat);
cursor = offersTable->cellAt(1, 1).firstCursorPosition();
cursor.insertText(tr("I do not want to receive any promotional information "
"from your company."), textFormat);
if (sendOffers)
cursor = offersTable->cellAt(0, 0).firstCursorPosition();
else
cursor = offersTable->cellAt(1, 0).firstCursorPosition();
cursor.insertText("X", boldFormat);
cursor.setPosition(topFrame->lastPosition());
cursor.insertBlock();
cursor.insertText(tr("Sincerely,"), textFormat);
cursor.insertBlock();
cursor.insertBlock();
cursor.insertBlock();
cursor.insertText(name);
printAction->setEnabled(true);
}
void MainWindow::createSample()
{
DetailsDialog dialog("Dialog with default values", this);
createLetter("Mr. Smith", "12 High Street\nSmall Town\nThis country",
dialog.orderItems(), true);
}
void MainWindow::openDialog()
{
DetailsDialog dialog(tr("Enter Customer Details"), this);
if (dialog.exec() == QDialog::Accepted)
createLetter(dialog.senderName(), dialog.senderAddress(),
dialog.orderItems(), dialog.sendOffers());
}
void MainWindow::printFile()
{
#ifndef QT_NO_PRINTER
QTextEdit *editor = static_cast<QTextEdit*>(letters->currentWidget());
QPrinter printer;
QPrintDialog *dialog = new QPrintDialog(&printer, this);
dialog->setWindowTitle(tr("Print Document"));
if (editor->textCursor().hasSelection())
dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection);
if (dialog->exec() != QDialog::Accepted)
return;
editor->print(&printer);
#endif
}
#include <QtGui>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.resize(640, 480);
window.show();
window.createSample();
return app.exec();
}
Set dialog extension
#include <QtGui>
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QDialog dlg;
QPushButton *btn = new QPushButton(QObject::tr("Expand/Collapse"),&dlg);
btn->setCheckable(true);
QVBoxLayout *lay = new QVBoxLayout(&dlg);
lay->addWidget(btn);
QLabel *ext = new QLabel(QObject::tr("Extension"));
dlg.setExtension(ext);
QObject::connect(btn, SIGNAL(toggled(bool)),&dlg, SLOT(showExtension(bool)));
dlg.exec();
return app.exec();
}
SIP Dialog Example
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
//! [Dialog header]
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog();
void reactToSIP();
private:
QRect desktopGeometry;
public slots:
void desktopResized(int screen);
};
//! [Dialog header]
#endif
#include <QtGui>
#include "dialog.h"
//! [Dialog constructor part1]
Dialog::Dialog()
{
desktopGeometry = QApplication::desktop()->availableGeometry(0);
setWindowTitle(tr("SIP Dialog Example"));
QScrollArea *scrollArea = new QScrollArea(this);
QGroupBox *groupBox = new QGroupBox(scrollArea);
groupBox->setTitle(tr("SIP Dialog Example"));
QGridLayout *gridLayout = new QGridLayout(groupBox);
groupBox->setLayout(gridLayout);
//! [Dialog constructor part1]
//! [Dialog constructor part2]
QLineEdit* lineEdit = new QLineEdit(groupBox);
lineEdit->setText(tr("Open and close the SIP"));
lineEdit->setMinimumWidth(220);
QLabel* label = new QLabel(groupBox);
label->setText(tr("This dialog resizes if the SIP is opened"));
label->setMinimumWidth(220);
QPushButton* button = new QPushButton(groupBox);
button->setText(tr("Close Dialog"));
button->setMinimumWidth(220);
//! [Dialog constructor part2]
//! [Dialog constructor part3]
if (desktopGeometry.height() < 400)
gridLayout->setVerticalSpacing(80);
else
gridLayout->setVerticalSpacing(150);
gridLayout->addWidget(label);
gridLayout->addWidget(lineEdit);
gridLayout->addWidget(button);
//! [Dialog constructor part3]
//! [Dialog constructor part4]
scrollArea->setWidget(groupBox);
QHBoxLayout* layout = new QHBoxLayout();
layout->addWidget(scrollArea);
setLayout(layout);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//! [Dialog constructor part4]
//! [Dialog constructor part5]
connect(button, SIGNAL(clicked()),
qApp, SLOT(closeAllWindows()));
connect(QApplication::desktop(), SIGNAL(workAreaResized(int)),
this, SLOT(desktopResized(int)));
}
//! [Dialog constructor part5]
//! [desktopResized() function]
void Dialog::desktopResized(int screen)
{
if (screen != 0)
return;
reactToSIP();
}
//! [desktopResized() function]
//! [reactToSIP() function]
void Dialog::reactToSIP()
{
QRect availableGeometry = QApplication::desktop()->availableGeometry(0);
if (desktopGeometry != availableGeometry) {
if (windowState() | Qt::WindowMaximized)
setWindowState(windowState() & ~Qt::WindowMaximized);
setGeometry(availableGeometry);
}
desktopGeometry = availableGeometry;
}
//! [reactToSIP() function]
#include <QtGui>
#include "dialog.h"
//! [main() function]
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Dialog dialog;
return dialog.exec();
}
//! [main() function]
What is This Dialog
Foundations of Qt Development\Chapter09\whatsthis\main.cpp
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QApplication>
#include "whatsthisdialog.h"
int main( int argc, char **argv )
{
QApplication app( argc, argv );
WhatsThisDialog dlg;
dlg.show();
return app.exec();
}
Foundations of Qt Development\Chapter09\whatsthis\whatsthisdialog.cpp
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <QPushButton>
#include <QCheckBox>
#include <QLabel>
#include <QGroupBox>
#include <QGridLayout>
#include "whatsthisdialog.h"
WhatsThisDialog::WhatsThisDialog() : QDialog()
{
QGroupBox *groupBox = new QGroupBox( tr("Group") );
QGridLayout *gbLayout = new QGridLayout( groupBox );
QCheckBox *checkBox = new QCheckBox( tr("Check!") );
QLabel *label = new QLabel( tr("label") );
QPushButton *pushButton = new QPushButton( tr("Push me!") );
gbLayout->addWidget( checkBox, 0, 0 );
gbLayout->addWidget( label, 0, 1 );
gbLayout->addWidget( pushButton, 1, 0, 1, 2 );
QGridLayout *dlgLayout = new QGridLayout( this );
dlgLayout->addWidget( groupBox, 0, 0 );
#ifndef true
checkBox->setWhatsThis( tr("This is a simple <i>What"s This help</i> for the check box.") );
#endif
checkBox->setWhatsThis( tr("<p style="white-space:pre">This is a simple <i>What"s This help</i> "
"for the check box.</p>") );
groupBox->setWhatsThis( tr("This is a group box <i>What"s This help</i>.<br>"
"Notice that it appears between and around the contained widgets.<br>"
"It is also spanning several lines.") );
label->setWhatsThis( tr("<p>It is possible to do lists.</p>"
"<ul>"
"<li>You can <i>format</i> text.</li>"
"<li><b>Bold</b> is possible too.</li>"
"<li>And the <font color="#22aaff">color</font> and "
"<font size="+2">size</font>.</li>"
"</ul>"
"<p>You can do ordered lists as well.</p>"
"<ol>"
"<li>First.</li>"
"<li>Second.</li>"
"<li>Third.</li>"
"</ol>") );
pushButton->setWhatsThis( tr("<img src=":/images/qt.png">"
"You can also insert images into your <i>What"s This help</i>.") );
}
Foundations of Qt Development\Chapter09\whatsthis\whatsthisdialog.h
/*
* Copyright (c) 2006-2007, Johan Thelin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of APress nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef WHATSTHISDIALOG_H
#define WHATSTHISDIALOG_H
#include <QDialog>
class WhatsThisDialog : public QDialog
{
public:
WhatsThisDialog();
};
#endif // WHATSTHISDIALOG_H