window.h
class MainWindow
{
/* ... */
public:
static MainWindow * instance;
void updateTree ();
private:
void updateBranch (QTreeWidgetItem *branch, QGraphicsItem *item);
void addLine(QString name, QVariant value);
void updateTable (QGraphicsItem * item);
};
void refreshTree ();
class TreeItem : public QTreeWidgetItem
{
public:
QGraphicsItem * shape;
};
window.cc
MainWindow * MainWindow::instance = NULL;
void refreshTree ()
{
if (MainWindow::instance != NULL)
MainWindow::instance->updateTree ();
}
void MainWindow::updateBranch (QTreeWidgetItem * branch, QGraphicsItem * item)
{
TreeItem * node = new TreeItem;
node->shape = item;
QString s = "item";
if (dynamic_cast (item) != NULL)
s = "rectangle";
else if (dynamic_cast (item) != NULL)
s = "ellipse";
node->setText (0, s);
QAbstractGraphicsShapeItem *shape = dynamic_cast (item);
if (shape != NULL)
{
node->setForeground (0, shape->pen().color());
node->setBackground (0, shape->brush().color());
}
branch->addChild (node);
for (QGraphicsItem * t : item->childItems())
updateBranch (node, t);
}
void MainWindow::updateTree()
{
ui->tree->clear ();
QTreeWidgetItem * branch = ui->tree->invisibleRootItem();
for (QGraphicsItem * item : scene->items ())
{
if (item->parentItem() == NULL)
updateBranch (branch, item);
}
ui->tree->expandAll();
}
void MainWindow::on_tree_itemDoubleClicked (QTreeWidgetItem *item, int column)
{
TreeItem * t = dynamic_cast (item);
if (t != NULL)
{
for (QGraphicsItem * s : scene->selectedItems())
s->setSelected (false);
t->shape->setSelected (true);
updateTable (t->shape);
}
}
void MainWindow::addLine (QString name, QVariant value)
{
int n = ui->prop->rowCount();
ui->prop->setRowCount (n+1);
QTableWidgetItem * t = new QTableWidgetItem;
t->setText (name);
ui->prop->setItem (n, 0, t);
t = new QTableWidgetItem;
t->setText (value.toString());
ui->prop->setItem (n, 1, t);
}
void MainWindow::updateTable (QGraphicsItem * item)
{
ui->prop->setRowCount(0);
ui->prop->setColumnCount(2);
ui->prop->setHorizontalHeaderLabels (QStringList() << "name" << "value");
addLine ("x", item->x());
addLine ("y", item->y());
}
shape.cc
void shapeDrop (QAbstractGraphicsShapeItem * shape, QGraphicsSceneDragDropEvent *event)
{
const QMimeData * data = event->mimeData();
if (data->hasColor())
{
/* ... */
refreshTree (); /* <--- */
}
if (data->hasFormat (shape_format))
{
/* ... */
refreshTree (); /* <--- */
}
}