tags:

views:

99

answers:

1

I've tried drawing a rectangle with text inside in a QGraphicsView. I get the text from the currently selected item in a QTreeWidget. The scene seems to sporadically show the text, sometimes it will, sometimes it won't.

void MainWindow::on_treewidget_itemSelectionChanged()
{
drawSectionFromProperties(ui->treewidget->currentItem());
}

void MainWindow::drawSectionFromProperties(QTreeWidgetItem *section)
{
        ui->graphicsview->setScene(new QGraphicsScene());
        ui->graphicsview->scene()->addRect(0,0,200,300,QPen(QColor(0,0,0)),QBrush(QColor(255,250,129)));
        QFont objectTitle;
        ui->graphicsview->scene()->addSimpleText(section->text(0),objectTitle);
}
A: 

Hmm, looks like you are creating a new scene on each item selection?

This isn't a very nice way to go :)

Better do the following:

  1. Create an 'QGraphicsScene* m_scene;' and 'QGraphicsSimpleTextItem* m_textItem' data members in your MainWindow class private section.
  2. In MainWindow::drawSectionFromProperties() do something like:

MainWindow::MainWindow(QWidget* parent, ...)
   : m_scene(0), m_textItem(0) 
{
...
}

// leave your on_treewidget_itemSelectionChanged as is

void MainWindow::drawSectionFromProperties(QTreeWidgetItem *section) 
{ 
    // setup things only ONE time on the first call
    if(!m_scene)
    {
        m_scene = new QGraphicsScene();
        ui->graphicsview->setScene(m_scene);
        m_textItem = ui->graphicsview->scene()->addSimpleText(QString());
    }

    // here only change text of existing item
    m_textItem->setText(section->text(0));
}

This way you won't be creating new scene on every item selection. Actually you need ONE scene and ONE item in it, no need to create them over and over and over again and stack one onto another like you currently do.

Cheers :)

dpimka
Your suggestion really helped organize my code better, but it seems this was the actual problem:m_textItem->setZValue(10);
eyecreate
oh, it might be. though I thought that you observe no text changes due to new scenes being created over and over - one on top of another - so it blinked. Maybe I didn't see something somewhere :) Anyway, glad you found the working solution :)
dpimka