gpt4 book ai didi

Python 类中的公共(public)方法?

转载 作者:行者123 更新时间:2023-12-01 03:50:49 25 4
gpt4 key购买 nike

我删除了代码以更好地理解我的问题。问题是是否有某种方法如何创建公共(public)方法之类的东西,以及我如何或是否完全误解了 OOP 概念。

我有一个主要类PlayerWindow,它只播放视频。然后是 ControlsWindow 类,仅用于我的开发、测试和维护目的(在全屏关闭时启动)。因此,我特别想成为它。无法弄清楚如何从 ControlsWindow 类中调用方法 play() 以及从内部调用方法,因为当我使用以下实例初始化 ControlsWindowPlayerWindow 然后我得到无限循环。

class ControlsWindow(QtGui.QWidget):

def __init__(self):
super(ControlsWindow, self).__init__()

self.playPauseButton = QtGui.QPushButton('Play', self)
self.show()


class PlayerWindow(QtGui.QWidget):

def __init__(self):
super(PlayerWindow, self).__init__()

# ...
self.mediaPlayer = self.playerInstance.media_player_new()
# ...
self.initUI()
self.play()

def initUI(self):
# ...
self.show()
self.controls_window = ControlsWindow()

def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return:
self.toggleControlsWindow()

def toggleControlsWindow(self):
if self.isFullScreen():
self.showNormal()
self.controls_window = ControlsWindow()
else:
self.controls_window.close()
self.showFullScreen()

def play(self):
self.mediaPlayer.play()


def main():
app = QtGui.QApplication(sys.argv)
player_window = PlayerWindow()

sys.exit(app.exec_())


if __name__ == "__main__":
main()

最佳答案

您可以将 PlayerWindow 的实例传递给 ControlsWindow 的类构造函数:

class ControlsWindow(QtGui.QWidget):

def __init__(self, parent): # Notice the new parent argument
super(ControlsWindow, self).__init__()
self.parent = parent

self.playPauseButton = QtGui.QPushButton('Play', self)
self.show()

# Now you can call the parent's (PlayerWindow) play() function:
self.parent.play()


class PlayerWindow(QtGui.QWidget):

def __init__(self):
super(PlayerWindow, self).__init__()

# ...
self.mediaPlayer = self.playerInstance.media_player_new()
# ...
self.initUI()
self.play()

def initUI(self):
# ...
self.show()
self.controls_window = ControlsWindow(self) # Pass a reference of PlayerWindow

def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return:
self.toggleControlsWindow()

def toggleControlsWindow(self):
if self.isFullScreen():
self.showNormal()
self.controls_window = ControlsWindow(self) # Pass a reference of PlayerWindow
else:
self.controls_window.close()
self.showFullScreen()

def play(self):
self.mediaPlayer.play()


def main():
app = QtGui.QApplication(sys.argv)
player_window = PlayerWindow()

sys.exit(app.exec_())


if __name__ == "__main__":
main()

希望这有帮助!

关于Python 类中的公共(public)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com