C++/Qt/QWidget — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Версия 17:21, 25 мая 2010

Analog Clock

<source lang="cpp"> /****************************************************************************

    • 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$
                                                                                                                                                        • /
  1. ifndef ANALOGCLOCK_H
  2. define ANALOGCLOCK_H
  3. include <QWidget>

class AnalogClock : public QWidget {

   Q_OBJECT

public:

   AnalogClock(QWidget *parent = 0);

protected:

   void paintEvent(QPaintEvent *event);

};

  1. endif


  1. include <QtGui>
  2. include "analogclock.h"

AnalogClock::AnalogClock(QWidget *parent)

   : QWidget(parent)

{

   QTimer *timer = new QTimer(this);

   connect(timer, SIGNAL(timeout()), this, SLOT(update()));

   timer->start(1000);
   setWindowTitle(tr("Analog Clock"));
   resize(200, 200);

}


void AnalogClock::paintEvent(QPaintEvent *)

{

   static const QPoint hourHand[3] = {
       QPoint(7, 8),
       QPoint(-7, 8),
       QPoint(0, -40)
   };
   static const QPoint minuteHand[3] = {
       QPoint(7, 8),
       QPoint(-7, 8),
       QPoint(0, -70)
   };
   QColor hourColor(127, 0, 127);
   QColor minuteColor(0, 127, 127, 191);
   int side = qMin(width(), height());
   QTime time = QTime::currentTime();
   QPainter painter(this);

   painter.setRenderHint(QPainter::Antialiasing);

   painter.translate(width() / 2, height() / 2);

   painter.scale(side / 200.0, side / 200.0);

   painter.setPen(Qt::NoPen);

   painter.setBrush(hourColor);


   painter.save();

   painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
   painter.drawConvexPolygon(hourHand, 3);
   painter.restore();

   painter.setPen(hourColor);

   for (int i = 0; i < 12; ++i) {
       painter.drawLine(88, 0, 96, 0);
       painter.rotate(30.0);
   }
   painter.setPen(Qt::NoPen);

   painter.setBrush(minuteColor);
   painter.save();
   painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
   painter.drawConvexPolygon(minuteHand, 3);
   painter.restore();

   painter.setPen(minuteColor);

   for (int j = 0; j < 60; ++j) {
       if ((j % 5) != 0)
           painter.drawLine(92, 0, 96, 0);
       painter.rotate(6.0);
   }

}


  1. include <QApplication>
  2. include "analogclock.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   AnalogClock clock;
   clock.show();
   return app.exec();

}


 </source>


Calendar widget

<source lang="cpp"> /****************************************************************************

    • 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$
                                                                                                                                                        • /
  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QWidget>

QT_BEGIN_NAMESPACE class QCalendarWidget; class QCheckBox; class QComboBox; class QDate; class QDateEdit; class QGridLayout; class QGroupBox; class QLabel; QT_END_NAMESPACE

class Window : public QWidget {

   Q_OBJECT

public:

   Window();

private slots:

   void localeChanged(int index);
   void firstDayChanged(int index);
   void selectionModeChanged(int index);
   void horizontalHeaderChanged(int index);
   void verticalHeaderChanged(int index);
   void selectedDateChanged();
   void minimumDateChanged(const QDate &date);
   void maximumDateChanged(const QDate &date);
   void weekdayFormatChanged();
   void weekendFormatChanged();
   void reformatHeaders();
   void reformatCalendarPage();

private:

   void createPreviewGroupBox();
   void createGeneralOptionsGroupBox();
   void createDatesGroupBox();
   void createTextFormatsGroupBox();
   QComboBox *createColorComboBox();
   QGroupBox *previewGroupBox;
   QGridLayout *previewLayout;
   QCalendarWidget *calendar;
   QGroupBox *generalOptionsGroupBox;
   QLabel *localeLabel;
   QLabel *firstDayLabel;
   QLabel *selectionModeLabel;
   QLabel *horizontalHeaderLabel;
   QLabel *verticalHeaderLabel;
   QComboBox *localeCombo;
   QComboBox *firstDayCombo;
   QComboBox *selectionModeCombo;
   QCheckBox *gridCheckBox;
   QCheckBox *navigationCheckBox;
   QComboBox *horizontalHeaderCombo;
   QComboBox *verticalHeaderCombo;
   QGroupBox *datesGroupBox;
   QLabel *currentDateLabel;
   QLabel *minimumDateLabel;
   QLabel *maximumDateLabel;
   QDateEdit *currentDateEdit;
   QDateEdit *minimumDateEdit;
   QDateEdit *maximumDateEdit;
   QGroupBox *textFormatsGroupBox;
   QLabel *weekdayColorLabel;
   QLabel *weekendColorLabel;
   QLabel *headerTextFormatLabel;
   QComboBox *weekdayColorCombo;
   QComboBox *weekendColorCombo;
   QComboBox *headerTextFormatCombo;
   QCheckBox *firstFridayCheckBox;
   QCheckBox *mayFirstCheckBox;

};

  1. endif


  1. include <QtGui>
  2. include "window.h"

Window::Window() {

   createPreviewGroupBox();
   createGeneralOptionsGroupBox();
   createDatesGroupBox();
   createTextFormatsGroupBox();
   QGridLayout *layout = new QGridLayout;
   layout->addWidget(previewGroupBox, 0, 0);
   layout->addWidget(generalOptionsGroupBox, 0, 1);
   layout->addWidget(datesGroupBox, 1, 0);
   layout->addWidget(textFormatsGroupBox, 1, 1);
   layout->setSizeConstraint(QLayout::SetFixedSize);
   setLayout(layout);
   previewLayout->setRowMinimumHeight(0, calendar->sizeHint().height());
   previewLayout->setColumnMinimumWidth(0, calendar->sizeHint().width());
   setWindowTitle(tr("Calendar Widget"));

}

void Window::localeChanged(int index) {

   calendar->setLocale(localeCombo->itemData(index).toLocale());

}

void Window::firstDayChanged(int index) {

   calendar->setFirstDayOfWeek(Qt::DayOfWeek(
                               firstDayCombo->itemData(index).toInt()));

}

void Window::selectionModeChanged(int index) {

   calendar->setSelectionMode(QCalendarWidget::SelectionMode(
                              selectionModeCombo->itemData(index).toInt()));

} void Window::horizontalHeaderChanged(int index) {

   calendar->setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat(
       horizontalHeaderCombo->itemData(index).toInt()));

} void Window::verticalHeaderChanged(int index) {

   calendar->setVerticalHeaderFormat(QCalendarWidget::VerticalHeaderFormat(
       verticalHeaderCombo->itemData(index).toInt()));

}

void Window::selectedDateChanged() {

   currentDateEdit->setDate(calendar->selectedDate());

}

void Window::minimumDateChanged(const QDate &date) {

   calendar->setMinimumDate(date);
   maximumDateEdit->setDate(calendar->maximumDate());

}

void Window::maximumDateChanged(const QDate &date) {

   calendar->setMaximumDate(date);
   minimumDateEdit->setDate(calendar->minimumDate());

}

void Window::weekdayFormatChanged() {

   QTextCharFormat format;
   format.setForeground(qvariant_cast<QColor>(
       weekdayColorCombo->itemData(weekdayColorCombo->currentIndex())));
   calendar->setWeekdayTextFormat(Qt::Monday, format);
   calendar->setWeekdayTextFormat(Qt::Tuesday, format);
   calendar->setWeekdayTextFormat(Qt::Wednesday, format);
   calendar->setWeekdayTextFormat(Qt::Thursday, format);
   calendar->setWeekdayTextFormat(Qt::Friday, format);

}

void Window::weekendFormatChanged() {

   QTextCharFormat format;
   format.setForeground(qvariant_cast<QColor>(
       weekendColorCombo->itemData(weekendColorCombo->currentIndex())));
   calendar->setWeekdayTextFormat(Qt::Saturday, format);
   calendar->setWeekdayTextFormat(Qt::Sunday, format);

}

void Window::reformatHeaders() {

   QString text = headerTextFormatCombo->currentText();
   QTextCharFormat format;
   if (text == tr("Bold")) {
       format.setFontWeight(QFont::Bold);
   } else if (text == tr("Italic")) {
       format.setFontItalic(true);
   } else if (text == tr("Green")) {
       format.setForeground(Qt::green);
   }
   calendar->setHeaderTextFormat(format);

}

void Window::reformatCalendarPage() {

   QTextCharFormat mayFirstFormat;
   if (mayFirstCheckBox->isChecked())
       mayFirstFormat.setForeground(Qt::red);
   QTextCharFormat firstFridayFormat;
   if (firstFridayCheckBox->isChecked())
       firstFridayFormat.setForeground(Qt::blue);
   QDate date(calendar->yearShown(), calendar->monthShown(), 1); 
   calendar->setDateTextFormat(QDate(date.year(), 5, 1), mayFirstFormat);
   date.setDate(date.year(), date.month(), 1);
   while (date.dayOfWeek() != Qt::Friday)
       date = date.addDays(1);
   calendar->setDateTextFormat(date, firstFridayFormat);

}

void Window::createPreviewGroupBox() {

   previewGroupBox = new QGroupBox(tr("Preview"));
   calendar = new QCalendarWidget;
   calendar->setMinimumDate(QDate(1900, 1, 1));
   calendar->setMaximumDate(QDate(3000, 1, 1));
   calendar->setGridVisible(true);
   connect(calendar, SIGNAL(currentPageChanged(int, int)),
           this, SLOT(reformatCalendarPage()));
   previewLayout = new QGridLayout;
   previewLayout->addWidget(calendar, 0, 0, Qt::AlignCenter);
   previewGroupBox->setLayout(previewLayout);

}

void Window::createGeneralOptionsGroupBox() {

   generalOptionsGroupBox = new QGroupBox(tr("General Options"));
   localeCombo = new QComboBox;
   int curLocaleIndex = -1;
   int index = 0;
   for (int _lang = QLocale::C; _lang <= QLocale::LastLanguage; ++_lang) {
       QLocale::Language lang = static_cast<QLocale::Language>(_lang);
       QList<QLocale::Country> countries = QLocale::countriesForLanguage(lang);
       for (int i = 0; i < countries.count(); ++i) {
           QLocale::Country country = countries.at(i);
           QString label = QLocale::languageToString(lang);
           label += QLatin1Char("/");
           label += QLocale::countryToString(country);
           QLocale locale(lang, country);
           if (this->locale().language() == lang && this->locale().country() == country)
               curLocaleIndex = index;
           localeCombo->addItem(label, locale);
           ++index;
       }
   }
   if (curLocaleIndex != -1)
       localeCombo->setCurrentIndex(curLocaleIndex);
   localeLabel = new QLabel(tr("&Locale"));
   localeLabel->setBuddy(localeCombo);
   firstDayCombo = new QComboBox;
   firstDayCombo->addItem(tr("Sunday"), Qt::Sunday);
   firstDayCombo->addItem(tr("Monday"), Qt::Monday);
   firstDayCombo->addItem(tr("Tuesday"), Qt::Tuesday);
   firstDayCombo->addItem(tr("Wednesday"), Qt::Wednesday);
   firstDayCombo->addItem(tr("Thursday"), Qt::Thursday);
   firstDayCombo->addItem(tr("Friday"), Qt::Friday);
   firstDayCombo->addItem(tr("Saturday"), Qt::Saturday);
   firstDayLabel = new QLabel(tr("Wee&k starts on:"));
   firstDayLabel->setBuddy(firstDayCombo);
   selectionModeCombo = new QComboBox;
   selectionModeCombo->addItem(tr("Single selection"),
                               QCalendarWidget::SingleSelection);
   selectionModeCombo->addItem(tr("None"), QCalendarWidget::NoSelection);
   selectionModeLabel = new QLabel(tr("&Selection mode:"));
   selectionModeLabel->setBuddy(selectionModeCombo);
   gridCheckBox = new QCheckBox(tr("&Grid"));
   gridCheckBox->setChecked(calendar->isGridVisible());
   navigationCheckBox = new QCheckBox(tr("&Navigation bar"));
   navigationCheckBox->setChecked(true);
   horizontalHeaderCombo = new QComboBox;
   horizontalHeaderCombo->addItem(tr("Single letter day names"),
                                  QCalendarWidget::SingleLetterDayNames);
   horizontalHeaderCombo->addItem(tr("Short day names"),
                                  QCalendarWidget::ShortDayNames);
   horizontalHeaderCombo->addItem(tr("None"),
                                  QCalendarWidget::NoHorizontalHeader);
   horizontalHeaderCombo->setCurrentIndex(1);
   horizontalHeaderLabel = new QLabel(tr("&Horizontal header:"));
   horizontalHeaderLabel->setBuddy(horizontalHeaderCombo);
   verticalHeaderCombo = new QComboBox;
   verticalHeaderCombo->addItem(tr("ISO week numbers"),
                                QCalendarWidget::ISOWeekNumbers);
   verticalHeaderCombo->addItem(tr("None"), QCalendarWidget::NoVerticalHeader);
   verticalHeaderLabel = new QLabel(tr("&Vertical header:"));
   verticalHeaderLabel->setBuddy(verticalHeaderCombo);
   connect(localeCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(localeChanged(int)));
   connect(firstDayCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(firstDayChanged(int)));
   connect(selectionModeCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(selectionModeChanged(int)));
   connect(gridCheckBox, SIGNAL(toggled(bool)),
           calendar, SLOT(setGridVisible(bool)));
   connect(navigationCheckBox, SIGNAL(toggled(bool)),
           calendar, SLOT(setNavigationBarVisible(bool)));
   connect(horizontalHeaderCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(horizontalHeaderChanged(int)));
   connect(verticalHeaderCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(verticalHeaderChanged(int)));
   QHBoxLayout *checkBoxLayout = new QHBoxLayout;
   checkBoxLayout->addWidget(gridCheckBox);
   checkBoxLayout->addStretch();
   checkBoxLayout->addWidget(navigationCheckBox);
   QGridLayout *outerLayout = new QGridLayout;
   outerLayout->addWidget(localeLabel, 0, 0);
   outerLayout->addWidget(localeCombo, 0, 1);
   outerLayout->addWidget(firstDayLabel, 1, 0);
   outerLayout->addWidget(firstDayCombo, 1, 1);
   outerLayout->addWidget(selectionModeLabel, 2, 0);
   outerLayout->addWidget(selectionModeCombo, 2, 1);
   outerLayout->addLayout(checkBoxLayout, 3, 0, 1, 2);
   outerLayout->addWidget(horizontalHeaderLabel, 4, 0);
   outerLayout->addWidget(horizontalHeaderCombo, 4, 1);
   outerLayout->addWidget(verticalHeaderLabel, 5, 0);
   outerLayout->addWidget(verticalHeaderCombo, 5, 1);
   generalOptionsGroupBox->setLayout(outerLayout);
   firstDayChanged(firstDayCombo->currentIndex());
   selectionModeChanged(selectionModeCombo->currentIndex());
   horizontalHeaderChanged(horizontalHeaderCombo->currentIndex());
   verticalHeaderChanged(verticalHeaderCombo->currentIndex());

}

void Window::createDatesGroupBox() {

   datesGroupBox = new QGroupBox(tr("Dates"));
   minimumDateEdit = new QDateEdit;
   minimumDateEdit->setDisplayFormat("MMM d yyyy");
   minimumDateEdit->setDateRange(calendar->minimumDate(),
                                 calendar->maximumDate());
   minimumDateEdit->setDate(calendar->minimumDate());
   minimumDateLabel = new QLabel(tr("&Minimum Date:"));
   minimumDateLabel->setBuddy(minimumDateEdit);
   currentDateEdit = new QDateEdit;
   currentDateEdit->setDisplayFormat("MMM d yyyy");
   currentDateEdit->setDate(calendar->selectedDate());
   currentDateEdit->setDateRange(calendar->minimumDate(),
                                 calendar->maximumDate());
   currentDateLabel = new QLabel(tr("&Current Date:"));
   currentDateLabel->setBuddy(currentDateEdit);
   maximumDateEdit = new QDateEdit;
   maximumDateEdit->setDisplayFormat("MMM d yyyy");
   maximumDateEdit->setDateRange(calendar->minimumDate(),
                                 calendar->maximumDate());
   maximumDateEdit->setDate(calendar->maximumDate());
   maximumDateLabel = new QLabel(tr("Ma&ximum Date:"));
   maximumDateLabel->setBuddy(maximumDateEdit);

   connect(currentDateEdit, SIGNAL(dateChanged(const QDate &)),
           calendar, SLOT(setSelectedDate(const QDate &)));
   connect(calendar, SIGNAL(selectionChanged()),
           this, SLOT(selectedDateChanged()));
   connect(minimumDateEdit, SIGNAL(dateChanged(const QDate &)),
           this, SLOT(minimumDateChanged(const QDate &)));
   connect(maximumDateEdit, SIGNAL(dateChanged(const QDate &)),
           this, SLOT(maximumDateChanged(const QDate &)));
   QGridLayout *dateBoxLayout = new QGridLayout;
   dateBoxLayout->addWidget(currentDateLabel, 1, 0);
   dateBoxLayout->addWidget(currentDateEdit, 1, 1);
   dateBoxLayout->addWidget(minimumDateLabel, 0, 0);
   dateBoxLayout->addWidget(minimumDateEdit, 0, 1);
   dateBoxLayout->addWidget(maximumDateLabel, 2, 0);
   dateBoxLayout->addWidget(maximumDateEdit, 2, 1);
   dateBoxLayout->setRowStretch(3, 1);
   datesGroupBox->setLayout(dateBoxLayout);

}

void Window::createTextFormatsGroupBox() {

   textFormatsGroupBox = new QGroupBox(tr("Text Formats"));
   weekdayColorCombo = createColorComboBox();
   weekdayColorCombo->setCurrentIndex(
           weekdayColorCombo->findText(tr("Black")));
   weekdayColorLabel = new QLabel(tr("&Weekday color:"));
   weekdayColorLabel->setBuddy(weekdayColorCombo);
   weekendColorCombo = createColorComboBox();
   weekendColorCombo->setCurrentIndex(
           weekendColorCombo->findText(tr("Red")));
   weekendColorLabel = new QLabel(tr("Week&end color:"));
   weekendColorLabel->setBuddy(weekendColorCombo);

   headerTextFormatCombo = new QComboBox;
   headerTextFormatCombo->addItem(tr("Bold"));
   headerTextFormatCombo->addItem(tr("Italic"));
   headerTextFormatCombo->addItem(tr("Plain"));
   headerTextFormatLabel = new QLabel(tr("&Header text:"));
   headerTextFormatLabel->setBuddy(headerTextFormatCombo);
   firstFridayCheckBox = new QCheckBox(tr("&First Friday in blue"));
   mayFirstCheckBox = new QCheckBox(tr("May &1 in red"));

   connect(weekdayColorCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(weekdayFormatChanged()));
   connect(weekendColorCombo, SIGNAL(currentIndexChanged(int)),
           this, SLOT(weekendFormatChanged()));
   connect(headerTextFormatCombo, SIGNAL(currentIndexChanged(const QString &)),
           this, SLOT(reformatHeaders()));
   connect(firstFridayCheckBox, SIGNAL(toggled(bool)),
           this, SLOT(reformatCalendarPage()));
   connect(mayFirstCheckBox, SIGNAL(toggled(bool)),
           this, SLOT(reformatCalendarPage()));
   QHBoxLayout *checkBoxLayout = new QHBoxLayout;
   checkBoxLayout->addWidget(firstFridayCheckBox);
   checkBoxLayout->addStretch();
   checkBoxLayout->addWidget(mayFirstCheckBox);
   QGridLayout *outerLayout = new QGridLayout;
   outerLayout->addWidget(weekdayColorLabel, 0, 0);
   outerLayout->addWidget(weekdayColorCombo, 0, 1);
   outerLayout->addWidget(weekendColorLabel, 1, 0);
   outerLayout->addWidget(weekendColorCombo, 1, 1);
   outerLayout->addWidget(headerTextFormatLabel, 2, 0);
   outerLayout->addWidget(headerTextFormatCombo, 2, 1);
   outerLayout->addLayout(checkBoxLayout, 3, 0, 1, 2);
   textFormatsGroupBox->setLayout(outerLayout);
   weekdayFormatChanged();
   weekendFormatChanged();
   reformatHeaders();
   reformatCalendarPage();

}

QComboBox *Window::createColorComboBox() {

   QComboBox *comboBox = new QComboBox;
   comboBox->addItem(tr("Red"), Qt::red);
   comboBox->addItem(tr("Blue"), Qt::blue);
   comboBox->addItem(tr("Black"), Qt::black);
   comboBox->addItem(tr("Magenta"), Qt::magenta);
   return comboBox;

}


  1. include <QtGui>
  2. include "window.h"

int main(int argv, char *args[]) {

   QApplication app(argv, args);
   Window window;
   window.show();
   return app.exec();

}


 </source>


Child widget

<source lang="cpp"> /****************************************************************************

    • 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 documentation 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$
                                                                                                                                                        • /
  1. include <QtGui>

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   QWidget *window = new QWidget();
   window->resize(320, 240);
   window->setWindowTitle(tr("Child widget"));
   window->show();

//! [create, position and show]

   QPushButton *button = new QPushButton(tr("Press me"), window);
   button->move(100, 100);
   button->show();

//! [create, position and show]

   return app.exec();

}


 </source>


Circle Widget

<source lang="cpp"> /****************************************************************************

    • 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$
                                                                                                                                                        • /
  1. ifndef CIRCLEWIDGET_H
  2. define CIRCLEWIDGET_H
  3. include <QWidget>

class CircleWidget : public QWidget {

   Q_OBJECT

public:

   CircleWidget(QWidget *parent = 0);
   void setFloatBased(bool floatBased);
   void setAntialiased(bool antialiased);
   QSize minimumSizeHint() const;
   QSize sizeHint() const;

public slots:

   void nextAnimationFrame();

protected:

   void paintEvent(QPaintEvent *event);

private:

   bool floatBased;
   bool antialiased;
   int frameNo;

};

  1. endif


  1. include <QtGui>
  2. include "circlewidget.h"
  3. include <stdlib.h>

CircleWidget::CircleWidget(QWidget *parent)

   : QWidget(parent)

{

   floatBased = false;
   antialiased = false;
   frameNo = 0;
   setBackgroundRole(QPalette::Base);
   setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

}

void CircleWidget::setFloatBased(bool floatBased) {

   this->floatBased = floatBased;
   update();

}

void CircleWidget::setAntialiased(bool antialiased) {

   this->antialiased = antialiased;
   update();

}

QSize CircleWidget::minimumSizeHint() const {

   return QSize(50, 50);

}

QSize CircleWidget::sizeHint() const {

   return QSize(180, 180);

}

void CircleWidget::nextAnimationFrame() {

   ++frameNo;
   update();

}

void CircleWidget::paintEvent(QPaintEvent *) {

   QPainter painter(this);
   painter.setRenderHint(QPainter::Antialiasing, antialiased);
   painter.translate(width() / 2, height() / 2);
   for (int diameter = 0; diameter < 256; diameter += 9) {
       int delta = abs((frameNo % 128) - diameter / 2);
       int alpha = 255 - (delta * delta) / 4 - diameter;

       if (alpha > 0) {
           painter.setPen(QPen(QColor(0, diameter / 2, 127, alpha), 3));
           if (floatBased) {
               painter.drawEllipse(QRectF(-diameter / 2.0, -diameter / 2.0,
                                          diameter, diameter));
           } else {
               painter.drawEllipse(QRect(-diameter / 2, -diameter / 2,
                                         diameter, diameter));
           }
       }
   }

}


  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QWidget>

QT_BEGIN_NAMESPACE class QLabel; QT_END_NAMESPACE class CircleWidget;

class Window : public QWidget {

   Q_OBJECT

public:

   Window();

private:

   QLabel *createLabel(const QString &text);
   QLabel *aliasedLabel;
   QLabel *antialiasedLabel;
   QLabel *intLabel;
   QLabel *floatLabel;
   CircleWidget *circleWidgets[2][2];

};

  1. endif


  1. include <QtGui>
  2. include "circlewidget.h"
  3. include "window.h"

Window::Window() {

   aliasedLabel = createLabel(tr("Aliased"));
   antialiasedLabel = createLabel(tr("Antialiased"));
   intLabel = createLabel(tr("Int"));
   floatLabel = createLabel(tr("Float"));
   QGridLayout *layout = new QGridLayout;
   layout->addWidget(aliasedLabel, 0, 1);
   layout->addWidget(antialiasedLabel, 0, 2);
   layout->addWidget(intLabel, 1, 0);
   layout->addWidget(floatLabel, 2, 0);
   QTimer *timer = new QTimer(this);
   for (int i = 0; i < 2; ++i) {
       for (int j = 0; j < 2; ++j) {
           circleWidgets[i][j] = new CircleWidget;
           circleWidgets[i][j]->setAntialiased(j != 0);
           circleWidgets[i][j]->setFloatBased(i != 0);
           connect(timer, SIGNAL(timeout()),
                   circleWidgets[i][j], SLOT(nextAnimationFrame()));
           layout->addWidget(circleWidgets[i][j], i + 1, j + 1);
       }
   }

   timer->start(100);
   setLayout(layout);
   setWindowTitle(tr("Concentric Circles"));

}

QLabel *Window::createLabel(const QString &text) {

   QLabel *label = new QLabel(text);
   label->setAlignment(Qt::AlignCenter);
   label->setMargin(2);
   label->setFrameStyle(QFrame::Box | QFrame::Sunken);
   return label;

}


  1. include <QApplication>
  2. include "window.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   Window window;
   window.show();
   return app.exec();

}


 </source>


Combo widget mapper

<source lang="cpp"> /****************************************************************************

    • 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$
                                                                                                                                                        • /
  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QWidget>

QT_BEGIN_NAMESPACE class QComboBox; class QDataWidgetMapper; class QLabel; class QLineEdit; class QPushButton; class QStandardItemModel; class QStringListModel; class QTextEdit; QT_END_NAMESPACE //! [Window definition] class Window : public QWidget {

   Q_OBJECT

public:

   Window(QWidget *parent = 0);

private slots:

   void updateButtons(int row);

private:

   void setupModel();
   QLabel *nameLabel;
   QLabel *addressLabel;
   QLabel *typeLabel;
   QLineEdit *nameEdit;
   QTextEdit *addressEdit;
   QComboBox *typeComboBox;
   QPushButton *nextButton;
   QPushButton *previousButton;
   QStandardItemModel *model;
   QStringListModel *typeModel;
   QDataWidgetMapper *mapper;

}; //! [Window definition]

  1. endif


  1. include <QtGui>
  2. include "window.h"

//! [Set up widgets] Window::Window(QWidget *parent)

   : QWidget(parent)

{

   setupModel();
   nameLabel = new QLabel(tr("Na&me:"));
   nameEdit = new QLineEdit();
   addressLabel = new QLabel(tr("&Address:"));
   addressEdit = new QTextEdit();
   typeLabel = new QLabel(tr("&Type:"));
   typeComboBox = new QComboBox();
   nextButton = new QPushButton(tr("&Next"));
   previousButton = new QPushButton(tr("&Previous"));
   nameLabel->setBuddy(nameEdit);
   addressLabel->setBuddy(addressEdit);
   typeLabel->setBuddy(typeComboBox);
   typeComboBox->setModel(typeModel);

//! [Set up widgets] //! [Set up the mapper]

   mapper = new QDataWidgetMapper(this);
   mapper->setModel(model);
   mapper->addMapping(nameEdit, 0);
   mapper->addMapping(addressEdit, 1);
   mapper->addMapping(typeComboBox, 2, "currentIndex");

//! [Set up the mapper] //! [Set up connections and layouts]

   connect(previousButton, SIGNAL(clicked()),
           mapper, SLOT(toPrevious()));
   connect(nextButton, SIGNAL(clicked()),
           mapper, SLOT(toNext()));
   connect(mapper, SIGNAL(currentIndexChanged(int)),
           this, SLOT(updateButtons(int)));
   QGridLayout *layout = new QGridLayout();
   layout->addWidget(nameLabel, 0, 0, 1, 1);
   layout->addWidget(nameEdit, 0, 1, 1, 1);
   layout->addWidget(previousButton, 0, 2, 1, 1);
   layout->addWidget(addressLabel, 1, 0, 1, 1);
   layout->addWidget(addressEdit, 1, 1, 2, 1);
   layout->addWidget(nextButton, 1, 2, 1, 1);
   layout->addWidget(typeLabel, 3, 0, 1, 1);
   layout->addWidget(typeComboBox, 3, 1, 1, 1);
   setLayout(layout);
   setWindowTitle(tr("Delegate Widget Mapper"));
   mapper->toFirst();

} //! [Set up connections and layouts] //! [Set up the model] void Window::setupModel() {

   QStringList items;
   items << tr("Home") << tr("Work") << tr("Other");
   typeModel = new QStringListModel(items, this);
   
   model = new QStandardItemModel(5, 3, this);
   QStringList names;
   names << "Alice" << "Bob" << "Carol" << "Donald" << "Emma";
   QStringList addresses;
   addresses << "<qt>123 Main Street
Market Town</qt>" << "<qt>PO Box 32
Mail Handling Service" "
Service City</qt>" << "<qt>The Lighthouse
Remote Island</qt>" << "<qt>47338 Park Avenue
Big City</qt>" << "<qt>Research Station
Base Camp
Big Mountain</qt>"; QStringList types; types << "0" << "1" << "2" << "0" << "2"; for (int row = 0; row < 5; ++row) { QStandardItem *item = new QStandardItem(names[row]); model->setItem(row, 0, item); item = new QStandardItem(addresses[row]); model->setItem(row, 1, item); item = new QStandardItem(types[row]); model->setItem(row, 2, item); }

} //! [Set up the model] //! [Slot for updating the buttons] void Window::updateButtons(int row) {

   previousButton->setEnabled(row > 0);
   nextButton->setEnabled(row < model->rowCount() - 1);

} //! [Slot for updating the buttons]


  1. include <QApplication>
  2. include "window.h"

int main(int argc, char **argv) {

   QApplication app(argc, argv);
   Window window;
   window.show();
   return app.exec();

}


 </source>


extends QWidget

<source lang="cpp"> Foundations of Qt Development\Chapter06\circlebar\circlebar.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
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
  1. include <QPaintEvent>
  2. include <QWheelEvent>
  3. include <QPainter>
  4. include "circlebar.h"

CircleBar::CircleBar( int value, QWidget *parent ) : QWidget( parent ) {

 m_value = value;
 
 QSizePolicy policy( QSizePolicy::Preferred, QSizePolicy::Preferred );
 policy.setHeightForWidth( true );
 setSizePolicy( policy );

} int CircleBar::heightForWidth( int width ) const {

 return width;

} QSize CircleBar::sizeHint() const {

 return QSize( 100, 100 );

} int CircleBar::value() const {

 return m_value;

} void CircleBar::setValue( int value ) {

 if( value < 0 )
   value = 0;
 
 if( value > 100 )
   value = 100;
   
 if( m_value == value )
   return;
   
 m_value = value;
 update();
 emit valueChanged( m_value );

} void CircleBar::paintEvent( QPaintEvent *event ) {

 int radius = width()/2;
 double factor = m_value/100.0;
 
 QPainter p( this );
 p.setPen( Qt::black );
 p.drawEllipse( 0, 0, width()-1, width()-1 );
 p.setBrush( Qt::black );
 p.drawEllipse( int(radius*(1.0-factor)), int(radius*(1.0-factor)), int((width()-1)*factor)+1, int((width()-1)*factor)+1 );

} void CircleBar::wheelEvent( QWheelEvent *event ) {

 event->accept();
 setValue( value() + event->delta()/20 );

}

Foundations of Qt Development\Chapter06\circlebar\circlebar.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.
*
*/
  1. ifndef CIRCLEBAR_H
  2. define CIRCLEBAR_H
  3. include <QWidget>

class CircleBar : public QWidget {

 Q_OBJECT

public:

 CircleBar( int value = 0, QWidget *parent = 0 );
 
 int value() const;
 
 int heightForWidth( int ) const;
 QSize sizeHint() const;  

public slots:

 void setValue( int );
 

signals:

 void valueChanged( int );
 

protected:

 void paintEvent( QPaintEvent* );
 void wheelEvent( QWheelEvent* );
 

private:

 int m_value;

};

  1. endif // CIRCLEBAR_H

Foundations of Qt Development\Chapter06\circlebar\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 
*     * 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.
*
*/
  1. include <QApplication>
  2. include <QSlider>
  3. include <QVBoxLayout>
  4. include "circlebar.h"

int main( int argc, char **argv ) {

 QApplication app( argc, argv );
 
 QWidget base;
 QVBoxLayout layout( &base );
 
 CircleBar bar;
 QSlider slider( Qt::Horizontal );
 
 layout.addWidget( &bar );
 layout.addWidget( &slider );
 
 QObject::connect( &slider, SIGNAL(valueChanged(int)), &bar, SLOT(setValue(int)) );
 QObject::connect( &bar, SIGNAL(valueChanged(int)), &slider, SLOT(setValue(int)) );
 
 base.show();
 
 return app.exec();

}


 </source>


How to compile and run Qt from command line

<source lang="cpp"> qmake layouts.pro C:\Qt\2009.04\qt\doc\src\snippets\layouts\debug>C:\Qt\2009.04\mingw\bin\mingw32-make go to debug folder and run the exe file


 </source>


Render Area

<source lang="cpp">

/****************************************************************************

    • 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$
                                                                                                                                                        • /
  1. ifndef RENDERAREA_H
  2. define RENDERAREA_H
  3. include <QPainterPath>
  4. include <QWidget>

class RenderArea : public QWidget {

   Q_OBJECT

public:

   RenderArea(const QPainterPath &path, QWidget *parent = 0);
   QSize minimumSizeHint() const;
   QSize sizeHint() const;

public slots:

   void setFillRule(Qt::FillRule rule);
   void setFillGradient(const QColor &color1, const QColor &color2);
   void setPenWidth(int width);
   void setPenColor(const QColor &color);
   void setRotationAngle(int degrees);

protected:

   void paintEvent(QPaintEvent *event);

private:

   QPainterPath path;
   QColor fillColor1;
   QColor fillColor2;
   int penWidth;
   QColor penColor;
   int rotationAngle;

};

  1. endif


  1. include <QtGui>
  2. include "renderarea.h"

RenderArea::RenderArea(const QPainterPath &path, QWidget *parent)

   : QWidget(parent), path(path)

{

   penWidth = 1;
   rotationAngle = 0;
   setBackgroundRole(QPalette::Base);

}

QSize RenderArea::minimumSizeHint() const {

   return QSize(50, 50);

}

QSize RenderArea::sizeHint() const {

   return QSize(100, 100);

}

void RenderArea::setFillRule(Qt::FillRule rule) {

   path.setFillRule(rule);
   update();

}

void RenderArea::setFillGradient(const QColor &color1, const QColor &color2) {

   fillColor1 = color1;
   fillColor2 = color2;
   update();

}

void RenderArea::setPenWidth(int width) {

   penWidth = width;
   update();

}

void RenderArea::setPenColor(const QColor &color) {

   penColor = color;
   update();

}

void RenderArea::setRotationAngle(int degrees) {

   rotationAngle = degrees;
   update();

}

void RenderArea::paintEvent(QPaintEvent *) {

   QPainter painter(this);
   painter.setRenderHint(QPainter::Antialiasing);

   painter.scale(width() / 100.0, height() / 100.0);
   painter.translate(50.0, 50.0);
   painter.rotate(-rotationAngle);
   painter.translate(-50.0, -50.0);

   painter.setPen(QPen(penColor, penWidth, Qt::SolidLine, Qt::RoundCap,
                       Qt::RoundJoin));
   QLinearGradient gradient(0, 0, 0, 100);
   gradient.setColorAt(0.0, fillColor1);
   gradient.setColorAt(1.0, fillColor2);
   painter.setBrush(gradient);
   painter.drawPath(path);

}


  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QWidget>

QT_BEGIN_NAMESPACE class QComboBox; class QLabel; class QSpinBox; QT_END_NAMESPACE class RenderArea;

class Window : public QWidget {

   Q_OBJECT

public:

   Window();

private slots:

   void fillRuleChanged();
   void fillGradientChanged();
   void penColorChanged();

private:

   void populateWithColors(QComboBox *comboBox);
   QVariant currentItemData(QComboBox *comboBox);
   enum { NumRenderAreas = 9 };
   RenderArea *renderAreas[NumRenderAreas];
   QLabel *fillRuleLabel;
   QLabel *fillGradientLabel;
   QLabel *fillToLabel;
   QLabel *penWidthLabel;
   QLabel *penColorLabel;
   QLabel *rotationAngleLabel;
   QComboBox *fillRuleComboBox;
   QComboBox *fillColor1ComboBox;
   QComboBox *fillColor2ComboBox;
   QSpinBox *penWidthSpinBox;
   QComboBox *penColorComboBox;
   QSpinBox *rotationAngleSpinBox;

};

  1. endif


  1. include <QtGui>
  2. include <math.h>
  3. include "renderarea.h"
  4. include "window.h"

const float Pi = 3.14159f;

Window::Window() {

   QPainterPath rectPath;
   rectPath.moveTo(20.0, 30.0);
   rectPath.lineTo(80.0, 30.0);
   rectPath.lineTo(80.0, 70.0);
   rectPath.lineTo(20.0, 70.0);
   rectPath.closeSubpath();
   QPainterPath roundRectPath;
   roundRectPath.moveTo(80.0, 35.0);
   roundRectPath.arcTo(70.0, 30.0, 10.0, 10.0, 0.0, 90.0);
   roundRectPath.lineTo(25.0, 30.0);
   roundRectPath.arcTo(20.0, 30.0, 10.0, 10.0, 90.0, 90.0);
   roundRectPath.lineTo(20.0, 65.0);
   roundRectPath.arcTo(20.0, 60.0, 10.0, 10.0, 180.0, 90.0);
   roundRectPath.lineTo(75.0, 70.0);
   roundRectPath.arcTo(70.0, 60.0, 10.0, 10.0, 270.0, 90.0);
   roundRectPath.closeSubpath();
   QPainterPath ellipsePath;
   ellipsePath.moveTo(80.0, 50.0);
   ellipsePath.arcTo(20.0, 30.0, 60.0, 40.0, 0.0, 360.0);
   QPainterPath piePath;
   piePath.moveTo(50.0, 50.0);
   piePath.arcTo(20.0, 30.0, 60.0, 40.0, 60.0, 240.0);
   piePath.closeSubpath();
   QPainterPath polygonPath;
   polygonPath.moveTo(10.0, 80.0);
   polygonPath.lineTo(20.0, 10.0);
   polygonPath.lineTo(80.0, 30.0);
   polygonPath.lineTo(90.0, 70.0);
   polygonPath.closeSubpath();
   QPainterPath groupPath;
   groupPath.moveTo(60.0, 40.0);
   groupPath.arcTo(20.0, 20.0, 40.0, 40.0, 0.0, 360.0);
   groupPath.moveTo(40.0, 40.0);
   groupPath.lineTo(40.0, 80.0);
   groupPath.lineTo(80.0, 80.0);
   groupPath.lineTo(80.0, 40.0);
   groupPath.closeSubpath();
   QPainterPath textPath;
   QFont timesFont("Times", 50);
   timesFont.setStyleStrategy(QFont::ForceOutline);
   textPath.addText(10, 70, timesFont, tr("Qt"));
   QPainterPath bezierPath;
   bezierPath.moveTo(20, 30);
   bezierPath.cubicTo(80, 0, 50, 50, 80, 80);
   QPainterPath starPath;
   starPath.moveTo(90, 50);
   for (int i = 1; i < 5; ++i) {
       starPath.lineTo(50 + 40 * cos(0.8 * i * Pi),
                       50 + 40 * sin(0.8 * i * Pi));
   }
   starPath.closeSubpath();
   renderAreas[0] = new RenderArea(rectPath);
   renderAreas[1] = new RenderArea(roundRectPath);
   renderAreas[2] = new RenderArea(ellipsePath);
   renderAreas[3] = new RenderArea(piePath);
   renderAreas[4] = new RenderArea(polygonPath);
   renderAreas[5] = new RenderArea(groupPath);
   renderAreas[6] = new RenderArea(textPath);
   renderAreas[7] = new RenderArea(bezierPath);
   renderAreas[8] = new RenderArea(starPath);
   Q_ASSERT(NumRenderAreas == 9);
   fillRuleComboBox = new QComboBox;
   fillRuleComboBox->addItem(tr("Odd Even"), Qt::OddEvenFill);
   fillRuleComboBox->addItem(tr("Winding"), Qt::WindingFill);
   fillRuleLabel = new QLabel(tr("Fill &Rule:"));
   fillRuleLabel->setBuddy(fillRuleComboBox);
   fillColor1ComboBox = new QComboBox;
   populateWithColors(fillColor1ComboBox);
   fillColor1ComboBox->setCurrentIndex(
           fillColor1ComboBox->findText("mediumslateblue"));
   fillColor2ComboBox = new QComboBox;
   populateWithColors(fillColor2ComboBox);
   fillColor2ComboBox->setCurrentIndex(
           fillColor2ComboBox->findText("cornsilk"));
   fillGradientLabel = new QLabel(tr("&Fill Gradient:"));
   fillGradientLabel->setBuddy(fillColor1ComboBox);
   fillToLabel = new QLabel(tr("to"));
   fillToLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
   penWidthSpinBox = new QSpinBox;
   penWidthSpinBox->setRange(0, 20);
   penWidthLabel = new QLabel(tr("&Pen Width:"));
   penWidthLabel->setBuddy(penWidthSpinBox);
   penColorComboBox = new QComboBox;
   populateWithColors(penColorComboBox);
   penColorComboBox->setCurrentIndex(
           penColorComboBox->findText("darkslateblue"));
   penColorLabel = new QLabel(tr("Pen &Color:"));
   penColorLabel->setBuddy(penColorComboBox);
   rotationAngleSpinBox = new QSpinBox;
   rotationAngleSpinBox->setRange(0, 359);
   rotationAngleSpinBox->setWrapping(true);
   rotationAngleSpinBox->setSuffix("\xB0");
   rotationAngleLabel = new QLabel(tr("&Rotation Angle:"));
   rotationAngleLabel->setBuddy(rotationAngleSpinBox);
   connect(fillRuleComboBox, SIGNAL(activated(int)),
           this, SLOT(fillRuleChanged()));
   connect(fillColor1ComboBox, SIGNAL(activated(int)),
           this, SLOT(fillGradientChanged()));
   connect(fillColor2ComboBox, SIGNAL(activated(int)),
           this, SLOT(fillGradientChanged()));
   connect(penColorComboBox, SIGNAL(activated(int)),
           this, SLOT(penColorChanged()));
   for (int i = 0; i < NumRenderAreas; ++i) {
       connect(penWidthSpinBox, SIGNAL(valueChanged(int)),
               renderAreas[i], SLOT(setPenWidth(int)));
       connect(rotationAngleSpinBox, SIGNAL(valueChanged(int)),
               renderAreas[i], SLOT(setRotationAngle(int)));
   }

   QGridLayout *topLayout = new QGridLayout;
   for (int i = 0; i < NumRenderAreas; ++i)
       topLayout->addWidget(renderAreas[i], i / 3, i % 3);
   QGridLayout *mainLayout = new QGridLayout;
   mainLayout->addLayout(topLayout, 0, 0, 1, 4);
   mainLayout->addWidget(fillRuleLabel, 1, 0);
   mainLayout->addWidget(fillRuleComboBox, 1, 1, 1, 3);
   mainLayout->addWidget(fillGradientLabel, 2, 0);
   mainLayout->addWidget(fillColor1ComboBox, 2, 1);
   mainLayout->addWidget(fillToLabel, 2, 2);
   mainLayout->addWidget(fillColor2ComboBox, 2, 3);
   mainLayout->addWidget(penWidthLabel, 3, 0);
   mainLayout->addWidget(penWidthSpinBox, 3, 1, 1, 3);
   mainLayout->addWidget(penColorLabel, 4, 0);
   mainLayout->addWidget(penColorComboBox, 4, 1, 1, 3);
   mainLayout->addWidget(rotationAngleLabel, 5, 0);
   mainLayout->addWidget(rotationAngleSpinBox, 5, 1, 1, 3);
   setLayout(mainLayout);
   fillRuleChanged();
   fillGradientChanged();
   penColorChanged();
   penWidthSpinBox->setValue(2);
   setWindowTitle(tr("Painter Paths"));

}

void Window::fillRuleChanged() {

   Qt::FillRule rule = (Qt::FillRule)currentItemData(fillRuleComboBox).toInt();
   for (int i = 0; i < NumRenderAreas; ++i)
       renderAreas[i]->setFillRule(rule);

}

void Window::fillGradientChanged() {

   QColor color1 = qvariant_cast<QColor>(currentItemData(fillColor1ComboBox));
   QColor color2 = qvariant_cast<QColor>(currentItemData(fillColor2ComboBox));
   for (int i = 0; i < NumRenderAreas; ++i)
       renderAreas[i]->setFillGradient(color1, color2);

}

void Window::penColorChanged() {

   QColor color = qvariant_cast<QColor>(currentItemData(penColorComboBox));
   for (int i = 0; i < NumRenderAreas; ++i)
       renderAreas[i]->setPenColor(color);

}

void Window::populateWithColors(QComboBox *comboBox) {

   QStringList colorNames = QColor::colorNames();
   foreach (QString name, colorNames)
       comboBox->addItem(name, QColor(name));

}

QVariant Window::currentItemData(QComboBox *comboBox) {

   return comboBox->itemData(comboBox->currentIndex());

}


  1. include <QApplication>
  2. include "window.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   Window window;
   window.show();
   return app.exec();

}


 </source>


Subclass QWidget

<source lang="cpp"> /****************************************************************************

    • 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 documentation 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$
                                                                                                                                                        • /
  1. include <QCheckBox>
  2. include <QMouseEvent>

class MyCheckBox : public QCheckBox { public:

   void mousePressEvent(QMouseEvent *event);

}; void MyCheckBox::mousePressEvent(QMouseEvent *event) {

   if (event->button() == Qt::LeftButton) {
       // handle left mouse button here
   } else {
       // pass on other buttons to base class
       QCheckBox::mousePressEvent(event);
   }

} class MyWidget : public QWidget { public:

   bool event(QEvent *event);

}; static const int MyCustomEventType = 1099; class MyCustomEvent : public QEvent { public:

   MyCustomEvent() : QEvent((QEvent::Type)MyCustomEventType) {}

}; bool MyWidget::event(QEvent *event) {

   if (event->type() == QEvent::KeyPress) {
    QKeyEvent *ke = static_cast<QKeyEvent *>(event);
    if (ke->key() == Qt::Key_Tab) {
       return true;
    }
   } else if (event->type() == MyCustomEventType) {
    MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event);
      return true;
   }
   return QWidget::event(event);

} int main() { }


 </source>


Subclass QWidget to do paint

<source lang="cpp"> /****************************************************************************

    • 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 documentation 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$
                                                                                                                                                        • /
  1. include <QtGui>

class MyWidget : public QWidget { public:

   MyWidget();

protected:

   void paintEvent(QPaintEvent *);

}; MyWidget::MyWidget() {

   QPalette palette(MyWidget::palette());
   palette.setColor(backgroundRole(), Qt::white);
   setPalette(palette);

} void MyWidget::paintEvent(QPaintEvent *) {

   QPainter painter(this);
   painter.setRenderHint(QPainter::Antialiasing);
   painter.setPen(Qt::darkGreen);
   painter.drawRect(1, 2, 6, 4);
   painter.setPen(Qt::darkGray);
   painter.drawLine(2, 8, 6, 2);

} int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   MyWidget widget;
   widget.show();
   return app.exec();

}


 </source>


Using QStatus tip event

<source lang="cpp"> /****************************************************************************

    • 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 documentation 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$
                                                                                                                                                        • /
  1. include <QtGui>
  2. include <QApplication>

class MainWindow : public QMainWindow { public:

   MainWindow(QWidget *parent = 0);

};

MainWindow::MainWindow(QWidget *parent)

   : QMainWindow(parent)

{

   QWidget *myWidget = new QWidget;
   myWidget->setStatusTip(tr("This is my widget."));
   setCentralWidget(myWidget);
   QMenu *fileMenu = menuBar()->addMenu(tr("File"));
   QAction *newAct = new QAction(tr("&New"), this);
   newAct->setStatusTip(tr("Create a new file."));
   fileMenu->addAction(newAct);
   statusBar()->showMessage(tr("Ready"));
   setWindowTitle(tr("QStatusTipEvent"));

}

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   MainWindow window;
   window.show();
   return app.exec();

}


 </source>


Wiggly Widget

<source lang="cpp"> /****************************************************************************

    • 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$
                                                                                                                                                        • /
  1. ifndef WIGGLYWIDGET_H
  2. define WIGGLYWIDGET_H
  3. include <QBasicTimer>
  4. include <QWidget>

class WigglyWidget : public QWidget {

   Q_OBJECT

public:

   WigglyWidget(QWidget *parent = 0);

public slots:

   void setText(const QString &newText) { text = newText; }

protected:

   void paintEvent(QPaintEvent *event);
   void timerEvent(QTimerEvent *event);

private:

   QBasicTimer timer;
   QString text;
   int step;

};

  1. endif


  1. include <QtGui>
  2. include "wigglywidget.h"

WigglyWidget::WigglyWidget(QWidget *parent)

   : QWidget(parent)

{

   setBackgroundRole(QPalette::Midlight);
   setAutoFillBackground(true);
   QFont newFont = font();
   newFont.setPointSize(newFont.pointSize() + 20);
   setFont(newFont);
   step = 0;
   timer.start(60, this);

}

void WigglyWidget::paintEvent(QPaintEvent * /* event */)

{

   static const int sineTable[16] = {
       0, 38, 71, 92, 100, 92, 71, 38,  0, -38, -71, -92, -100, -92, -71, -38
   };
   QFontMetrics metrics(font());
   int x = (width() - metrics.width(text)) / 2;
   int y = (height() + metrics.ascent() - metrics.descent()) / 2;
   QColor color;
   QPainter painter(this);

   for (int i = 0; i < text.size(); ++i) {
       int index = (step + i) % 16;
       color.setHsv((15 - index) * 16, 255, 191);
       painter.setPen(color);
       painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400),
                        QString(text[i]));
       x += metrics.width(text[i]);
   }

}

void WigglyWidget::timerEvent(QTimerEvent *event)

{

   if (event->timerId() == timer.timerId()) {
       ++step;
       update();
   } else {
 QWidget::timerEvent(event);
   }

}


  1. ifndef DIALOG_H
  2. define DIALOG_H
  3. include <QDialog>

class Dialog : public QDialog {

   Q_OBJECT

public:

   Dialog(QWidget *parent = 0);

};

  1. endif


  1. include <QtGui>
  2. include "dialog.h"
  3. include "wigglywidget.h"

Dialog::Dialog(QWidget *parent)

   : QDialog(parent)

{

   WigglyWidget *wigglyWidget = new WigglyWidget;
   QLineEdit *lineEdit = new QLineEdit;
   QVBoxLayout *layout = new QVBoxLayout;
   layout->addWidget(wigglyWidget);
   layout->addWidget(lineEdit);
   setLayout(layout);
   connect(lineEdit, SIGNAL(textChanged(QString)),
           wigglyWidget, SLOT(setText(QString)));
   lineEdit->setText(tr("Hello world!"));
   setWindowTitle(tr("Wiggly"));
   resize(360, 145);

}


  1. include <QApplication>
  2. include "dialog.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   Dialog dialog;
   dialog.show();
   return app.exec();

}


 </source>