考慮下面給出的最低限度的例子class Main: def __init__(self): self.name='' self.age='' def setinfo(self): self.name=input() self.age=input() def run(self): self.startWin=QWidget() self.setinfo() dnd=DragDrop('Drop Photo here',self.startWin) self.startWin.show() sys.exit(app.exec_()) def showWin(self,file_path): self.mainWin=QWidget() self.label1=QLabel(self.name,self.mainWin) self.label2=QLabel(self.age,self.mainWin) self.photo = QLabel(self.mainWin) pixmap = QPixmap(file_path) self.photo.setPixmap(pixmap) self.mainWin.show()class DragDrop(QLabel): def __init__(self, title, parent): super().__init__(title, parent) self.setAcceptDrops(True) def dragEnterEvent(self, event): if event.mimeData().hasImage: event.accept() else: event.ignore() def dropEvent(self, event): file_path = event.mimeData().urls()[0].toLocalFile() self.showWin(file_path)app = QApplication([])instance=Main()instance.run()現(xiàn)在,我想要的是將文件放入 dnd(拖放 QLabel)后立即調用 Main 類的 showWin 函數(shù),以顯示該人的姓名、年齡和照片。但是,當然,來自 DragDrop 類的調用將不起作用,因為 showWin 函數(shù)屬于 Main 類。我什至無法創(chuàng)建該類的對象然后調用它,因為我想在已經(jīng)運行的實例中進行更改。我該如何克服這種情況?我已經(jīng)嘗試過的:我嘗試將可變數(shù)據(jù)類型(如列表)傳遞到 DragDrop 類的構造函數(shù)中,并對其進行更改。但問題是,需要再次單擊運行函數(shù)中的某個按鈕才能使用該路徑并調用 showWin。第二種解決方案是通過__get__在 run 函數(shù)中使用方法直接覆蓋 QLabel 對象的事件方法(不形成類)。但我認為這太特定于語言了。我正在嘗試為此找到一個基于面向對象的通用解決方案。
如何在 PyQt5 中解決這個問題?
函數(shù)式編程
2024-01-24 15:42:13