QFormLayout
-
Hello dear users i need help with adding rows to QFormLayout. I will paste code. As you can see in code i am adding label to QFormLayout but when i try to add this label second time it not showing second time. How can i add this label more times to QFormLayout ?
Just to mention i cant make label 2,3,4,5 etc. Because i need to add these labels in running program. User will fill text in textbox and it will add label to QFromLayout. So i need to create them by some way in the running program.
import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtWidgets import QMainWindow from PyQt5.QtWidgets import * from PyQt5 import QtWidgets class Window2(QMainWindow and QWidget): def __init__(self): super().__init__() self.setGeometry(200, 250, 500, 600) self.setWindowTitle("Scroll") self.label = QtWidgets.QLabel(self) self.label.setText("Hello") self.update() self.formLayout = QFormLayout() self.groupBox = QGroupBox("This Is Group Box") self.groupBox.setFixedWidth(200) self.groupBox.setLayout(self.formLayout) self.formLayout.addRow(self.label) self.formLayout.addRow(self.label) # SECOND TIME NOT WORKING self.scroll = QScrollArea() self.scroll.setFixedWidth(200) self.scroll.setWidget(self.groupBox) self.scroll.setFixedHeight(400) self.layout = QVBoxLayout(self) self.layout.addWidget(self.scroll) self.show() if __name__ == "__main__": app = QApplication(sys.argv) window = Window2() sys.exit(app.exec())
-
@Samuel-Bachorik
Yes, you can only add a given widget once somewhere. If you need to add two labels onto your form, you need to create two separate label instances. -
@JonB hello thank you for your reply a lot. Just want to ask you. It is possible to create new labels in running program ? For example i mean. Button conected to function and that function create new label and this label will have text from textbox. Is it possible to create function like this ? By some way i need to create new labels always when button click.
-
@Samuel-Bachorik
Yes, your code is already "create new labels in running program ":self.label = QtWidgets.QLabel(self)
That creates a label at run-time when that statement is hit.
You will need a
self.label1 = QtWidgets.QLabel(self)
and a separateself.label2 = QtWidgets.QLabel(self)
, so that you can goself.formLayout.addRow(self.label1) self.formLayout.addRow(self.label2)
If you need more than this, an "unlimited" number of labels, you can call
QtWidgets.QLabel(self)
as many times as you need to, including in response to button presses or whatever. If you need to maintain references to those labels, you would need to create aself.labels = []
list/array, and append the newly-created labels to that, so that you maintain your own list of references.