Important: Please read the Qt Code of Conduct -

[solved] Centering a QTextFrame

  • I'm trying to accomplish something with QTextEdit that may not be possible but perhaps someone has an idea that doesn't involve creating my own layout manager.

    My goal is to find a way of horizontally centering a fixed width QTextFrame within it's parent QTextFrame. In the simplest form the parent frame would be the the associated QTextDocument's rootFrame. Please note that I am not trying to center the text in the fixed width QTextFrame (that's easy). I'm trying to center the frame itself. This appears to be equivalent to having dynamic left and right margins that keep the frame centered with respect to its parent.

    I've tried several approaches but none of them have worked. I'm wondering if adding a dummy empty left and right floating frames (with frame format positions set to QTextFrameFormat::FloatLeft and QTextFrameFormat::FloatRight) bracketing the actual frame of interest would work. If someone has tried this approach I'd appreciate hearing from you.

    Or perhaps there is a simple way to accomplish my goal that I've overlooked. Anyone have any ideas?

  • Well, I think I've solved the problem; at least all my tests seem to work now. The idea is to not use a QTextFrame directly but instead use a 1 by 3 table as a surrogate for formatting purposes. The table's column 0 and 2 cells remain empty and variable while the middle column 1 cell becomes the surrogate QTextFrame. Setting the tables QTextTableFormat alignment to Qt:AlignHCenter then produces the desired result as it appears that the middle table cell will act just like a QTextFrame for most purposes.

    Actually this solution appears more general than my original problem since it centers a QTextFrame or block independent of whether or not it is of fixed width.

Log in to reply