Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Файл примера rsslisting.cpp
xml/rsslisting/rsslisting.cpp

 /****************************************************************************
 **
 ** Copyright (C) 2004-2008 Trolltech ASA. All rights reserved.
 **
 ** This file is part of the example classes of the Qt Toolkit.
 **
 ** This file may be used under the terms of the GNU General Public
 ** License versions 2.0 or 3.0 as published by the Free Software
 ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
 ** included in the packaging of this file.  Alternatively you may (at
 ** your option) use any later version of the GNU General Public
 ** License if such license has been publicly approved by Trolltech ASA
 ** (or its successors, if any) and the KDE Free Qt Foundation. In
 ** addition, as a special exception, Trolltech gives you certain
 ** additional rights. These rights are described in the Trolltech GPL
 ** Exception version 1.2, which can be found at
 ** http://www.trolltech.com/products/qt/gplexception/ and in the file
 ** GPL_EXCEPTION.txt in this package.
 **
 ** Please review the following information to ensure GNU General
 ** Public Licensing requirements will be met:
 ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If
 ** you are unsure which license is appropriate for your use, please
 ** review the following information:
 ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
 ** or contact the sales department at sales@trolltech.com.
 **
 ** In addition, as a special exception, Trolltech, as the sole
 ** copyright holder for Qt Designer, grants users of the Qt/Eclipse
 ** Integration plug-in the right for the Qt/Eclipse Integration to
 ** link to functionality provided by Qt Designer and its related
 ** libraries.
 **
 ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
 ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
 ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly
 ** granted herein.
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 **
 ****************************************************************************/

 /*
 rsslisting.cpp

 Предоставляет виджет для отображения элементов новостей из источников новостей RDF.
 RDF это формат основанный на XML для хранения элементов информаци (смотрите
 http://www.w3.org/RDF/ для получения подробностей).

 Сам виджет предоставляет простой интерфейс пользователя для указания
 URL источника новостей и контролирования загрузки новостей.

 Виджет скачивает и парсит XML асинхронно, подавая 
 данные ридеру XML по частям. Это позволяет пользователю прерывать
 его операции и так же позволяет читать очень большие источники данных.
 */

 #include <QtCore>
 #include <QtGui>
 #include <QtNetwork>

 #include "rsslisting.h"

 /*
     Конструирует виджет RSSListing с простым интерфейсом пользователя и устанавливает
     ридер XML для использования пользовательского класса обработки.

     Интерфейс пользователя состоит из строки ввода, двух кнопок и
     виджета просмотра списка. Строка ввода используется для ввода URL источника новостей;
     кнопки начинают и отменяют процесс чтения
     новостей.
 */

 RSSListing::RSSListing(QWidget *parent)
     : QWidget(parent)
 {
     lineEdit = new QLineEdit(this);
     lineEdit->setText("http://labs.trolltech.com/blogs/feed");

     fetchButton = new QPushButton(tr("Fetch"), this);
     abortButton = new QPushButton(tr("Abort"), this);
     abortButton->setEnabled(false);

     treeWidget = new QTreeWidget(this);
     connect(treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*, int)),
             this, SLOT(itemActivated(QTreeWidgetItem*)));
     QStringList headerLabels;
     headerLabels << tr("Title") << tr("Link");
     treeWidget->setHeaderLabels(headerLabels);
     treeWidget->header()->setResizeMode(QHeaderView::ResizeToContents);

     connect(&http, SIGNAL(readyRead(const QHttpResponseHeader &)),
              this, SLOT(readData(const QHttpResponseHeader &)));

     connect(&http, SIGNAL(requestFinished(int, bool)),
              this, SLOT(finished(int, bool)));

     connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(fetch()));
     connect(fetchButton, SIGNAL(clicked()), this, SLOT(fetch()));
     connect(abortButton, SIGNAL(clicked()), &http, SLOT(abort()));

     QVBoxLayout *layout = new QVBoxLayout(this);

     QHBoxLayout *hboxLayout = new QHBoxLayout;

     hboxLayout->addWidget(lineEdit);
     hboxLayout->addWidget(fetchButton);
     hboxLayout->addWidget(abortButton);

     layout->addLayout(hboxLayout);
     layout->addWidget(treeWidget);

     setWindowTitle(tr("RSS listing example"));
     resize(640,480);
 }

 /*
     Начинает скачивать данные из источника новостей указанного в виджете
     строки ввода.

     Строка ввода делается только для чтения что бы не дать пользователю изменять её
     содержимое во время скачивания; это только для косметических целей.
     Кнопка скачивания отключается, а кнопка отмены становится активной что бы позволить
     пользователю прервать обработку. Вид списка создаётся и мы
     определяем последний элемент равным 0, означая, что здесь нет
     существующих элементов в списке.

     Обработчику HTTP поставляется необработанное содержимое строки  ввода и
     скачка инициализируется. Мы храним значение ID возвращаемое обработчиком HTTP 
     для будующих ссылок.
 */

 void RSSListing::fetch()
 {
     lineEdit->setReadOnly(true);
     fetchButton->setEnabled(false);
     abortButton->setEnabled(true);
     treeWidget->clear();

     xml.clear();

     QUrl url(lineEdit->text());

     http.setHost(url.host());
     connectionId = http.get(url.path());
 }

 /*
     Считывает данные, полученные из источника RDF.

     Мы считываем все доступные данные и передаём их потоковому XML
     ридеру. Затем мы вызываем функцию парсинга XML.

     Если парсинг не удаётся по любой причине, мы отменяем скачку.
 */

 void RSSListing::readData(const QHttpResponseHeader &resp)
 {
     if (resp.statusCode() != 200)
         http.abort();
     else {
         xml.addData(http.readAll());
         parseXml();
     }
 }

 /*
     Заканчивает обработку запроса HTTP.

     Поведение по умолчанию сохраняет редактор текста в режиме только для чтения.

     Если происходит ошибка, интерфейс пользователя становится доступен
     пользователю для дальнейшего ввода, позволяя новой скачке
     начаться.

     Если запрос получения HTTP завершается, мы делаем
     интерфейс пользователя доступным пользователю для дальнейшего ввода.
 */

 void RSSListing::finished(int id, bool error)
 {
     if (error) {
         qWarning("Received error during HTTP fetch.");
         lineEdit->setReadOnly(false);
         abortButton->setEnabled(false);
         fetchButton->setEnabled(true);
     }
     else if (id == connectionId) {
         lineEdit->setReadOnly(false);
         abortButton->setEnabled(false);
         fetchButton->setEnabled(true);
     }
 }

 /*
     Парсит данные XML и создаёт соответственно элементы treeWidget.
 */
 void RSSListing::parseXml()
 {
     while (!xml.atEnd()) {
         xml.readNext();
         if (xml.isStartElement()) {
             if (xml.name() == "item")
                 linkString = xml.attributes().value("rss:about").toString();
             currentTag = xml.name().toString();
         } else if (xml.isEndElement()) {
             if (xml.name() == "item") {

                 QTreeWidgetItem *item = new QTreeWidgetItem;
                 item->setText(0, titleString);
                 item->setText(1, linkString);
                 treeWidget->addTopLevelItem(item);

                 titleString.clear();
                 linkString.clear();
             }

         } else if (xml.isCharacters() && !xml.isWhitespace()) {
             if (currentTag == "title")
                 titleString += xml.text().toString();
             else if (currentTag == "link")
                 linkString += xml.text().toString();
         }
     }
     if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
         qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
         http.abort();
     }
 }

 /*
     Открывает ссылку в браузере
 */
 void RSSListing::itemActivated(QTreeWidgetItem * item)
 {
     QDesktopServices::openUrl(QUrl(item->text(1)));
 }


Copyright © 2008 Trolltech Торговые марки
Qt 4.3.5