PyQt:如何在另一个类中重用方法(def)?

时间:2018-07-14 23:26:40

标签: python python-3.x pyqt pyqt5

我想问一下如何重用另一个类中的一个类的方法(def)。

在我的以下代码中,def center中有一个方法class FirstWindow。我想在def center中重用此class SecondWindow,而不必再次将相同的代码粘贴到class SecondWindow中。

我进行了很多搜索,但找不到答案。有人可以给我些帮助吗?谢谢!

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class FirstWindow(QWidget):
    close_signal = pyqtSignal()
    def __init__(self):
        super(FirstWindow, self).__init__()

        self.btn = QToolButton(self)
        self.btn.setText("click")

        self.btn.clicked.connect(second.handle_click)
        self.btn.clicked.connect(self.hide)
        self.close_signal.connect(self.close)

        self.show()

        self.center()

    def closeEvent(self, event):
        self.close_signal.emit()
        self.close()

    def center(self):   # Question: How to reuse this method in class SecondWindow? 
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

class SecondWindow(QWidget):
    def __init__(self):
        super(SecondWindow, self).__init__()
        self.resize(200, 200)
        self.setStyleSheet("background: black")

    def handle_click(self):
        if not self.isVisible():
            self.show()

    def handle_close(self):
        self.close()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    second = SecondWindow()
    first = FirstWindow()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

由于您希望多个小部件共享同一方法,因此只能执行一项功能:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

def center(widget):
    qr = widget.frameGeometry()
    cp = QDesktopWidget().availableGeometry().center()
    qr.moveCenter(cp)
    widget.move(qr.topLeft())


class FirstWindow(QWidget):
    close_signal = pyqtSignal()
    def __init__(self):
        super(FirstWindow, self).__init__()

        self.btn = QToolButton(self)
        self.btn.setText("click")

        self.btn.clicked.connect(second.handle_click)
        self.btn.clicked.connect(self.hide)
        self.close_signal.connect(self.close)

        self.show()
        center(self)

    def closeEvent(self, event):
        self.close_signal.emit()
        self.close()

class SecondWindow(QWidget):
    def __init__(self):
        super(SecondWindow, self).__init__()
        self.resize(200, 200)
        self.setStyleSheet("background: black")
        center(self)

    def handle_click(self):
        if not self.isVisible():
            self.show()

    def handle_close(self):
        self.close()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    second = SecondWindow()
    first = FirstWindow()
    sys.exit(app.exec_())