I have QLabel and this width shrink to content size. How can I set size policy to grow-only policy? for example, I set text to "12345" and QLabel should grow to minimal size to show this content, but when I set "12" this wouldnt shrink and stay old size.
Well, unless you don't need to use the space you want to recover for others widgets, you can use a QtGui.QSpacerItem
; see QSpacerItem Class Reference .
You can set the size policy to the spacer item.
Note: This gets done automatically when you're using QtDesigner.
In QtDesigner, it should look like this:
The label has a cyan background for ilustrative purposes.
Here, you have some code sample:
Warning: the code has been written in Python. I don't know your lenguage preferences. But the interface is pretty much the same. Goog luck.
import PyQt4.QtGui as gui
import PyQt4.QtCore as core
import sys
if __name__ == "__main__":
app = gui.QApplication(sys.argv)
widget = gui.QWidget(None)
label = gui.QLabel(widget)
label.setStyleSheet("background-color: cyan;")
label.setMinimumWidth(10)
label.setText("Write some text above")
text = gui.QLineEdit(widget)
layout = gui.QVBoxLayout(widget)
hlayout = gui.QHBoxLayout(widget) # This layout will contains
# the label and a sacer item.
layout.addWidget(text)
hlayout.addWidget(label) # Add the label.
# Create the spacer.
spacerItem = gui.QSpacerItem(40, 20, gui.QSizePolicy.Expanding, gui.QSizePolicy.Minimum)
hlayout.addItem(spacerItem) # Add the spacer.
layout.addItem(hlayout)
# Slot for change the text of the label.
@core.pyqtSlot()
def on_textChanged():
label.setText(text.text())
text.textChanged.connect(on_textChanged)
widget.show()
sys.exit(app.exec_())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.