考慮下面給出的最低限度的例子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()現在,我想要的是將文件放入 dnd(拖放 QLabel)后立即調用 Main 類的 showWin 函數,以顯示該人的姓名、年齡和照片。但是,當然,來自 DragDrop 類的調用將不起作用,因為 showWin 函數屬于 Main 類。我什至無法創建該類的對象然后調用它,因為我想在已經運行的實例中進行更改。我該如何克服這種情況?我已經嘗試過的:我嘗試將可變數據類型(如列表)傳遞到 DragDrop 類的構造函數中,并對其進行更改。但問題是,需要再次單擊運行函數中的某個按鈕才能使用該路徑并調用 showWin。第二種解決方案是通過__get__在 run 函數中使用方法直接覆蓋 QLabel 對象的事件方法(不形成類)。但我認為這太特定于語言了。我正在嘗試為此找到一個基于面向對象的通用解決方案。
1 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
您可以使用自定義信號。在 DragDrop 中創建信號并在 中發出dropEvent:
image_dropped = pyqtSignal(str)
def dropEvent(self, event):
file_path = event.mimeData().urls()[0].toLocalFile()
self.image_dropped.emit(file_path)
將信號連接到showWinMain:
def run(self):
self.startWin=QWidget()
self.setinfo()
dnd=DragDrop('Drop Photo here',self.startWin)
dnd.image_dropped.connect(self.showWin)
self.startWin.show()
sys.exit(app.exec_())
添加回答
舉報
0/150
提交
取消