如何从PyQT5 / PyQT6QLineEdit
中动态生成的文本获取文本?
我只能从最后创建的小部件中提取文本,但我想检查所有创建的小部件并提取所有不为空的数据 - 并将数据排列到列表中。QLineEdit
这是一个最低限度可重现的示例:
import sys
from PyQt6.QtWidgets import QWidget, QApplication, QGridLayout, QHBoxLayout, QPushButton, QLineEdit
class Main(QWidget):
def __init__(self):
super().__init__()
self.row_counter = 0
self.le = ''
self.grid = QGridLayout()
self.grid_line_url = QGridLayout()
self.grid.addLayout(self.generate_line_url(), 0, 0)
self.grid.addWidget(self.push_button(name='ok!',
do=self.text_from_line_edit), 1, 0)
self.setLayout(self.grid)
def h_box(self, *args):
box = QHBoxLayout()
if args:
for widget in args:
box.addWidget(widget)
return box
def push_button(self, width=None, height=None, name=None, do=None):
but = QPushButton()
if width is not None and height is not None:
but.setFixedSize(width, height)
if name:
but.setText(name)
if do:
but.clicked.connect(do)
return but
def line_edit(self):
self.le = QLineEdit()
self.le.setFixedHeight(30)
return self.le
def generate_line_url(self):
self.grid_line_url.addLayout(self.h_box(self.line_edit(),
self.push_button(width=30,
height=30,
name='+',
do=self.generate_line_url)), self.row_counter, 0, 1, 3)
self.row_counter += 1
return self.grid_line_url
def text_from_line_edit(self):
print(self.le.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec())
你写的东西很奇怪,但它有效。
主要.py
此外,还提出了此方法作为解决方案,以防有人发现它有用: