2

I want to map two pointers in a QMap Object to store their relation. The key pointer points to a QTextBlock while the value pointer points to a widget. The aim is to update the position of the widget in relation to the position of the QTextBlock in the QPlainTextEdit when something in the QPlainTextEdit changes. The widget should get destroyed when the QTextBlock gets destroyed.

However, I'm not familiar with the behaviour of a QTextBlock in QPlainTextEdit. Though the firstVisibleBlock() method does not seem to return a pointer to a QTextBlock in the QPlainTextEdit I create a new QTextBlock with the QTextBlock from the QPlainTextEdit as parameter.

QTextBlock* CodeEditor::getBlockAtPosition(QPoint position) {

  QTextBlock block = firstVisibleBlock();
  while (true)
    {
      QRectF blockDim = blockBoundingGeometry(block).translated(contentOffset());
      if (position.y() <= blockDim.bottom() && position.y() >= blockDim.top())
        {
          break;
        }
      else if (block.blockNumber() + 1 < blockCount())
        block = block.next();
      else break;
    }
  return new QTextBlock (block);
}

Well, this seems to work because when I add new lines (QTextBlocks) to the QPlainTextEdit by hitting Enter/Return the attributes of the object behind the pointer change as intended. Which means if u insert a line before the relevant block, the blockNumber increases and the geometry/position changes.

But if you delete the relevant line (backspace/del) the pointer still points to a QTextBlock in the QPlainTextEdit - I have no idea how or why. When I call the isValid() method on the pointer value it returns true.

So, why are the attributes changing tho it's a new QTextBlock object? Is there a way to get a direct pointer or a reference to a QTextBlock in the QPlainTextEdit?

Ben
  • 807
  • 1
  • 8
  • 22
  • Have you tried to insertText() in the "dangling" QTextBlock ? Did you check the QTextBlock::isVisible property ? – ibizaman Jul 17 '13 at 15:30

1 Answers1

0

I know this is an old question, but I stumbled on it while looking for a solution to a similar problem, so I'm answering to document what I found which may be relevant for future searches.

I was trying to attach some external marker to be tied to a specific line even when editing inserts / deletes other lines. The problem was that even if the line attached to the marker was deleted, the block object was reused and so the marker got moved to a wrong position.

The solution was using the user data feature of the text block. When a block gets "deleted" and reused, the user data is removed. So My marker inherits from QTextBlockUserData and I set the marker as the user data for the block, and hold a reference to the block in the marker. Then, the validity test is simply to compare the marker object and the user data held by the block. Seems to work.

Photon
  • 3,182
  • 1
  • 15
  • 16