I'm trying to call a function in the main class with the PyQt5 button "dropEvent
" event in Python. Although the "print("setText")
" command in the function works, the next "self.lbl_1.setText("setText")
" command does not work.
Code:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Button(QPushButton):
def __init__(self, title, parent):
super(Button, self).__init__(title, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('text/plain'):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
self.setText(event.mimeData().text())
MainWindow().lbl_setText()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 200, 150)
self.setWindowTitle("Example")
self.setup()
def setup(self):
self.btn_quit = Button('Quit', self)
self.btn_quit.clicked.connect(QApplication.instance().quit)
self.btn_quit.resize(self.btn_quit.sizeHint())
self.btn_quit.move(90, 100)
self.btn_quit.setAcceptDrops(True)
self.le_drag = QLineEdit('', self)
self.le_drag.setDragEnabled(True)
self.le_drag.move(50, 50)
self.lbl_1= QLabel('Hi', self)
self.lbl_1.move(50, 10)
def closeEvent(self, event: QCloseEvent):
reply = QMessageBox.question(self, 'Message', "r u sure!",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def lbl_setText(self):
print("setText")
self.lbl_1.setText("setText")
def main():
app = QApplication([])
app.setStyle("Fusion")
mainWin = MainWindow()
mainWin.show()
app.exec()
if __name__ == '__main__':
main()
CodePudding user response:
The interaction does not occur between classes but between objects, in your case you are creating a new MainWindow object that is not visible so you have that problem. A simple way to communicate objects in Qt is through signals and slots:
class Button(QPushButton):
dropped = pyqtSignal(str)
# ....
def dropEvent(self, event):
self.setText(event.mimeData().text())
self.dropped.emit(self.text())
class MainWindow(QMainWindow):
# ...
def setup(self):
self.btn_quit = Button('Quit', self)
self.btn_quit.clicked.connect(QApplication.quit)
self.btn_quit.resize(self.btn_quit.sizeHint())
self.btn_quit.move(90, 100)
self.btn_quit.setAcceptDrops(True)
self.le_drag = QLineEdit('', self)
self.le_drag.setDragEnabled(True)
self.le_drag.move(50, 50)
self.lbl_1= QLabel('Hi', self)
self.lbl_1.move(50, 10)
self.btn_quit.dropped.connect(self.lbl_1.setText) # <---
# ...