PyQt5如何动态生成窗口组件?
PyQt5如何动态生成窗口组件?
有时候希望一次得到多个不确定的字符串输入,下面代码在 self.label[i] = QtWidgets.QLabel(label_str)行出现错误提示,“ has no attribute label ”错误,组件不支持下标,恳请高人指教。
#getstringdef getInputboxs(label_strs):
'''Return the utf-8 string of text that you write in the lineEdit.
label_strs: the string as the prompt of the label in the dialog.'''
from PyQt5 import QtGui, QtCore, QtWidgets
import sys
width=800
#height=100
class MyWindows(QtWidgets.QDialog):
input_str = ''
def __init__(self):
QtWidgets.QDialog.__init__(self)
self.setWindowTitle(u'GUI Input')
n=len(label_strs)
self.resize(width,60+35*n)
self.ok = QtWidgets.QPushButton('确定')
self.ok.clicked.connect(self.getLine)
self.clean = QtWidgets.QPushButton('清空')
self.clean.clicked.connect(self.cleaning)
self.cancel = QtWidgets.QPushButton('取消')
self.cancel.clicked.connect(self.quit)
#self.setWindowTitle(label_strs)
for i, label_str in enumerate(label_strs):
self.label[i] = QtWidgets.QLabel(label_str)
self.lineEdit[i] = QtWidgets.QLineEdit()
layout = QtWidgets.QGridLayout()
layout.addWidget(self.ok, 2*n-1, 1, 1, 1)
layout.addWidget(self.clean, 2*n-1, 2, 1, 1)
layout.addWidget(self.cancel, 2*n-1, 3, 1, 1)
for i, label_str in enumerate(label_strs):
layout.addWidget(self.label[i], 2*i, 0, 1, 4)
layout.addWidget(self.lineEdit[i], 2*i+1, 0, 1, 4)
self.setLayout(layout)
MyWindow.input_str = ['' *len(label_strs)]
def getLine(self):
for i in range(len(label_strs)):
#MyWindows.input_str = str(self.lineEdit.text().toUtf8())
MyWindows.input_str[i] = str(self.lineEdit[i].text())
self.close()
def cleaning(self):
for i in range(len(label_strs)):
self.lineEdit[i].setText('')
def quit(self):
MyWindows.input_str = ['' *len(label_strs)]
self.close()
app = QtWidgets.QApplication(sys.argv)
win = MyWindows()
win.show()
app.exec_()
return MyWindows.input_str
if __name__ == '__main__':
pre_str = getInputboxs(['输入字符串1','输入字符串2','输入字符串3'])
print (pre_str)
pre_str = getInputbox('输入字符串')
print (pre_str)
回答:
类变量未先声明就使用。应该先声明如
self.label = [None] * len(label_strs)
回答:
谢谢,可以啦
以上是 PyQt5如何动态生成窗口组件? 的全部内容, 来源链接: utcz.com/a/28664.html