xml
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QGraphicsScene> namespace Ui { class MainWindow; } class Param { public: QString name; QString value; }; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void readFile(QString fileName); void createShape(QGraphicsItem *&target, QString name, QList<Param> list); private: Ui::MainWindow *ui; QGraphicsScene * scene; }; #endif // MAINWINDOW_H
#include “mainwindow.h” #include “ui_mainwindow.h”
#include <QFile> #include <QXmlStreamReader> #include <QXmlStreamAttribute>
#include <QGraphicsRectItem> #include <QGraphicsEllipseItem>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene; ui->graphicsView->setScene (scene);
scene->addLine (0, 0, 100, 100, QColor ("blue"));
// readFile ("../xml/mainwindow.ui"); readFile ("../xml/data.xml");
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::readFile (QString fileName) {
QFile file (fileName); if (file.open (QFile::ReadOnly | QFile::Text )) { QTreeWidgetItem * branch = ui->treeWidget->invisibleRootItem(); QGraphicsItem * target = NULL; QXmlStreamReader reader (&file); while (! reader.atEnd()) { if (reader.isStartElement()) { QString s = reader.name().toString(); QTreeWidgetItem * item = new QTreeWidgetItem; item->setText (0, s); item->setForeground (0, QColor ("blue")); branch->addChild (item); branch = item;
QList <Param> list; // for (QXmlStreamAttribute a : reader.attributes()) for (auto a : reader.attributes()) { auto node = new QTreeWidgetItem; QString t = a.name().toString() + "=" + a.value().toString(); node->setText (0, t); node->setForeground (0, QColor ("green")); item->addChild (node);
Param p; p.name = a.name().toString(); p.value = a.value().toString(); list.append (p); /* list << p; */ }
createShape (target, s, list); } else if (reader.isCharacters()) { QString s = reader.text().toString().simplified(); if (s != "") { QTreeWidgetItem * item = new QTreeWidgetItem; item->setText (0, s); item->setForeground (0, QColor ("orange")); branch->addChild (item); } } else if (reader.isEndElement()) { branch = branch->parent(); } reader.readNext(); } ui->treeWidget->expandAll(); }
}
void MainWindow::createShape (QGraphicsItem * & target,
QString name, QList <Param> list)
{
QGraphicsRectItem * shape = NULL; if (name == "rectangle") shape = new QGraphicsRectItem; else if (name == "ellipse") shape = new QGraphicsRectItem;
if (shape != NULL) { shape->setRect(10, 10, 100, 40); shape->setFlag (QGraphicsItem::ItemIsMovable);
for (Param p : list) if (p.name == "pen") shape->setPen (QColor (p.value)); else if (p.name == "brush") shape->setBrush (QColor (p.value));
if (target == NULL) scene->addItem (shape); else shape->setParentItem (target); }
} </code>
xml.txt · Last modified: 2017/03/27 15:10 by 127.0.0.1