При нажатии на кнопку возвращает значение
Всем привет. Есть кнопка
self.toolButton = QtWidgets.QToolButton(Dialog)
self.toolButton.setGeometry(QtCore.QRect(640, 10, 31, 21))
self.toolButton.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.toolButton.setObjectName("toolButton")
Есть обработчик
ui.toolButton.clicked.connect(from_to_copy)
функция которая обрабатывается
def from_to_copy():
dirlist = ui.file_dialog_2.getExistingDirectory()
ui.lineEdit.setText(dirlist)
global from_copy
from_copy = dirlist
Суть проста, при нажатии на кнопку, открывается диалоговое окно, выбираю папку и он сохраняет ее в переменную dirlist. Мне эти данные нужны в другой функции, которые привязаны к другой кнопке. Я сделал следующим образом: создал переменную global from_copy, присваюиваю значение и потом работаю с этой переменной в другой функции. Но, что то мне подсказывает что это прям костыль. Как вообще правильно обрабатывать кнопку, что бы оно возвращало значение. Типо того
def from_to_copy():
dirlist = ui.file_dialog_2.getExistingDirectory()
ui.lineEdit.setText(dirlist)
return dirlist
form_copy = ui.toolButton.clicked.connect(from_to_copy)
Ответы (1 шт):
Автор решения: S. Nick
→ Ссылка
Попробуйте так:
from PyQt5 import QtCore, QtGui, QtWidgets
class Main(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.toolButton = QtWidgets.QToolButton(text="Выбираю папку")
self.toolButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.toolButton.clicked.connect(self.from_to_copy)
self.toolButton_2 = QtWidgets.QToolButton(text="Другая кнопка")
self.toolButton_2.clicked.connect(self.from_to_other)
self.dirlist = '' # !!!
self.lineEdit = QtWidgets.QLineEdit(readOnly=True)
self.label = QtWidgets.QLabel()
layout = QtWidgets.QGridLayout(self)
layout.addWidget(self.lineEdit, 0, 0)
layout.addWidget(self.toolButton, 0, 1)
layout.addWidget(self.label, 1, 0)
layout.addWidget(self.toolButton_2, 1, 1)
def from_to_copy(self):
self.dirlist = QtWidgets.QFileDialog.getExistingDirectory( # !!!
self, 'Выбрать папку для ...'
)
if self.dirlist:
self.lineEdit.setText(self.dirlist)
else:
self.lineEdit.clear()
def from_to_other(self):
self.label.setText(self.dirlist) # !!!
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Main()
w.resize(400, 150)
w.show()
sys.exit(app.exec_())
