views:

55

answers:

3

How to place a QTextEdit with left and right margins in a QVBoxLayout? I could use, of course, a QHBoxLayout, place the QTextEdit into that horizontal layout in between to spacings (addSpacing(40)) and only then the horizontal layout could add into the vertical layout, but want to know if there is a direct way of doing that.

+4  A: 

There is

void QLayout::setContentsMargins ( int left, int top, int right, int bottom );

but this sets a margin around the whole thing. If you want margins on just the QTextEdit and nothing else in the layout then you have to use the QHBoxLayout approach you mentioned. I'm not aware of any other tricks to get around that.

Troubadour
This was usefull too. Thanks.
Narek
A: 

You don't mention if you are using Qt Designer or doing this by hand in code.

In code: The QLayout class has a setContentsMargins property that you can use to set the left and right to whatever you want. There are even two flavors, one that takes left, top, right, bottom as separate arguments and one that takes a QMargins object.

Qt Designer: Just set the margins properties directly.

Matt T
+1  A: 

If you want the margins only for your QTextEdit and not any other element in the QVerticalLayout you can use css styling for that. You just need to give a name to the QTextEdit object (like "myMarginsTextEdit") and style it, eg:

QTextEdit#myMarginsTextEdit { left-margin: 40px; right-margin: 40px; }

If you are not using css to style your application you can still use it only to style that item. You can do it like this (imagine your QtextEdit variable is call "textEditItem"):

textEditItem.setStyleSheet("QTextEdit{margin-left:40px;margin-right:40px}");

The other option is use content margins in the vertical layout but then it is applied to all elements.

Hope it helps.

cnebrera
Unfortunately css does not work. The reason my be the layout where the QTwxtEdit is.
Narek
Can you write down the code you are using? It is very weird that css styling cannot add the margins you need, I have use it ton of times without problems.
cnebrera
m_TextEdit = new QTextEdit; m_TextEdit->setStyleSheet("left-margin:140px;right-margin:140px"); m_generalLayout = new QVBoxLayout; m_generalLayout->addLayout(m_bLayout); m_generalLayout->addStretch(); m_generalLayout->addWidget(m_qLabel); m_generalLayout->addWidget(m_TextEdit); m_generalLayout->addWidget(m_aLabel); m_generalLayout->addWidget(m_aLieEdit); m_generalLayout->addStretch(); m_generalLayout->addLayout(m_buttonLayout); m_generalLayout->addSpacing(15); setLayout(m_generalLayout);
Narek
BYW I get:Unknown property left-marginUnknown property right-margin
Narek
Need to be written setStyleSheet("margin-left:40px;margin-right:40px"); Please correct your answer in order to make possible for me to choose you answer as the correct.
Narek
Ups it is true, margin word is first, sorry my mistake, correcting it... XD. Has it work properly then?
cnebrera
Yes, sure. Thank you.
Narek