PyQt5如何动态生成窗口组件?
PyQt5如何动态生成窗口组件?
有时候希望一次得到多个不确定的字符串输入,下面代码在 self.label[i] = QtWidgets.QLabel(label_str)行出现错误提示,“ has no attribute label ”错误,组件不支持下标,恳请高人指教。
#getstring
def 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类变量未先声明就使用。应该先声明如
谢谢,可以啦