开发者

QGraphicsView missing text on some draws

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.

voi开发者_开发知识库d 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);
}


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜