PDA

View Full Version : QTextFrameFormat issues.



ImperialPenguin
27th November 2012, 17:38
I'm having a problem setting the margins and putting a border around them in a QTextEdit. I want my program to behave similar to OpenOffice, where the margins and text size scale along with the resizing of the window. I have the following code to calculate the margins as a percentage of the widget size and adjust the text so that 65 characters takes up a line of the available space.


void NCTextEdit::autoScale() {
margins = this->geometry().width() * 0.2;
float ww = this->geometry().width() - margins;
QFont font;
font.setFamily("Courier");
font.setPointSize(12);
float fw = QFontMetrics(font).width("M") * 65; // 65 characters per line;
if (fw == 0)
fw = ww;

fontZoom = ww / fw;
margins /= 2;
setFontPointSize(12*fontZoom);

QTextFrameFormat format;
format.setTopMargin(margins);
format.setBottomMargin(margins);
format.setLeftMargin(margins);
format.setRightMargin(margins);
format.setBorder(2);
format.setBorderBrush(QBrush(QColor(0, 0, 0, 50)));
format.setBorderStyle(QTextFrameFormat::BorderStyl e_Solid);
document()->rootFrame()->setFrameFormat(format);
}


I call this function from the resizeEvent code. Everything almost works as expected. The only hiccup is when the program first starts. When the QTextEdit is empty and the program initially starts up, the border does not appear. Neither does the cursor. Even when I click on the QTextEdit to make it active, the cursor doesn't appear. When I start typing, or resize the window, the border comes up and the cursor will be visible. This is less than ideal, because the cursor is an important visual cue to the user that it is okay to start typing.

I know that the code above is being called on startup, but I figured that maybe there was something about it getting called before the initialization function of the QMainWindow is done that it didn't like. So I put a QTimer to call the code after a small amount of time. That didn't solve the two problems above.

The whole thing works if I put some text in there ahead of time, but I don't want text in there, the user isn't going to expect their blank text document to not be blank. I'm not sure why it suddenly starts working if I resize the window manually, but not when the resizeEvent is called when the window is initially setup, and not when the scaling function is called after the window is setup.

Is there something I'm missing to make the widget update?

ImperialPenguin
28th November 2012, 02:30
I accidentally stumbled upon the answer. I added a QTextBlockFormat change to the code and it all started working. So if anyone else is having the same problem, updating the QTextBlockFormat should fix it.