Как сохранить в переменную и отобразить в lineEdit?
Вопрос в том, что пишу простой генератор паролей используя PyQt5.
Вопрос как сохранить и отобразить в lineEdit значение переменной password, чтобы сгенерированный пароль отобразился и сохранился также в файле.
Моя реализация:
from PyQt5 import QtCore, QtGui, QtWidgets
import random
class Ui_Dialog(object):
def __init__(self):
self.password = ''
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(318, 114)
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(Dialog)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
self.lineEdit_2.setSizePolicy(sizePolicy)
self.lineEdit_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.lineEdit_2.setObjectName("lineEdit_2")
self.horizontalLayout.addWidget(self.lineEdit_2)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.checkBox = QtWidgets.QCheckBox(Dialog)
self.checkBox.setObjectName("checkBox")
self.horizontalLayout.addWidget(self.checkBox)
self.verticalLayout.addLayout(self.horizontalLayout)
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
#self.checkBox.stateChanged.connect(self.event_password)
self.pushButton.clicked.connect(self.display_and_save_password)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Длина пароля:"))
self.checkBox.setText(_translate("Dialog", "Сохранить в .txt"))
self.pushButton.setText(_translate("Dialog", "СГЕНЕРИРОВАТЬ ПАРОЛЬ"))
def generate_password(self):
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower = 'abcdefghijklmnopqrstuvwxyz'
numbers = '0123456789'
symbols = '[]{}()*;/,._-'
all = lower + upper + numbers + symbols
length = int(self.lineEdit_2.text())
self.password = ''.join(random.sample(all, length))
print(self.password)
def save_in_file(self):
with open ('password.txt', 'w') as file:
file.write(self.password)
def display_and_save_password(self):
self.lineEdit.setText(self.password)
save_password = self.save_in_file()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
Ответы (1 шт):
Автор решения: S. Nick
→ Ссылка
Не изменяйте код, сгенерированный Qt Designer. Создайте другой класс, который наследуется от соответствующего виджета, и используйте созданный класс для его заполнения.
Сделать вызов метода self.generate_password() и свставить несколько проверок.
from PyQt5 import QtCore, QtGui, QtWidgets
import random
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(318, 114)
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(Dialog)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
self.lineEdit_2.setSizePolicy(sizePolicy)
self.lineEdit_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.lineEdit_2.setObjectName("lineEdit_2")
self.horizontalLayout.addWidget(self.lineEdit_2)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.checkBox = QtWidgets.QCheckBox(Dialog)
self.checkBox.setObjectName("checkBox")
self.horizontalLayout.addWidget(self.checkBox)
self.verticalLayout.addLayout(self.horizontalLayout)
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Длина пароля:"))
self.checkBox.setText(_translate("Dialog", "Сохранить в .txt"))
self.pushButton.setText(_translate("Dialog", "СГЕНЕРИРОВАТЬ ПАРОЛЬ"))
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self):
super().__init__()
self.setupUi(self)
self.password = ''
#self.checkBox.stateChanged.connect(self.event_password)
self.pushButton.clicked.connect(self.display_and_save_password)
def generate_password(self):
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower = 'abcdefghijklmnopqrstuvwxyz'
numbers = '0123456789'
symbols = '[]{}()*;/,._-'
all = lower + upper + numbers + symbols
length = int(self.lineEdit_2.text())
self.password = ''.join(random.sample(all, length))
print(self.password)
def save_in_file(self):
with open ('password.txt', 'w') as file:
file.write(self.password)
def display_and_save_password(self):
if not self.lineEdit_2.text():
msg = QtWidgets.QMessageBox.information(self,
'Внимание', 'Укажите длину пароля.')
return
self.generate_password() # +++
self.lineEdit.setText(self.password)
if self.checkBox.isChecked(): # +++
save_password = self.save_in_file()
msg = QtWidgets.QMessageBox.information(self,
'Успех', 'Пароль сохранен в .txt.')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
