gpt4 book ai didi

python - python pyqt5类引用

转载 作者:太空宇宙 更新时间:2023-11-04 02:39:40 25 4
gpt4 key购买 nike

panel.py 中,类中引用 buttonA 的类无法发出信号。

但在panel2.py中引用buttonA类即可实现如果要在panel.py类中重复使用buttonA类,出现这样的问题如何处理。尝试继承buttonA类只能出现一次btnA1

buttonA.py

#!/usr/bin/env python
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, QApplication

class ButtonA(QWidget):
def __init__(self):
super().__init__()

def createButton(self):
self.btnA1 = QPushButton("btnA1", self)
self.btnA1.pressed.connect(self.onbtnA1Pressed)
self.btnA1.released.connect(self.onbtnA1Released)
vbox = QVBoxLayout()
vbox.addWidget(self.btnA1)
return vbox

def onbtnA1Pressed(self):
self.btnA1.setText("btnA1 clicked")

def onbtnA1Released(self):
self.btnA1.setText("btnA1")

面板.py

#!/usr/bin/env python
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QApplication
import sys, buttonA

class Panel(QWidget):
def __init__(self):
super().__init__()

def createPanel(self):
a1 = buttonA.ButtonA()
a2 = buttonA.ButtonA()
v1 = a1.createButton()
v2 = a2.createButton()

vbox = QVBoxLayout()
vbox.addLayout(v1)
vbox.addLayout(v2)
self.setLayout(vbox)

if __name__ == "__main__":
app = QApplication(sys.argv)
p = Panel()
p.createPanel()
p.show()
sys.exit(app.exec_())

panel2.py

#!/usr/bin/env python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
import buttonA, sys

app = QApplication(sys.argv)
w = QWidget()

a1 = buttonA.ButtonA()
a2 = buttonA.ButtonA()
v1 = a1.createButton()
v2 = a2.createButton()

vbox = QVBoxLayout()
vbox.addLayout(v1)
vbox.addLayout(v2)
w.setLayout(vbox)
w.show()

sys.exit(app.exec_())

最佳答案

panel.py 中,在您的 createPanel 函数中,您必须在声明实例变量时使用实例,在本例中为 self

这应该有效:

面板.py

#!/usr/bin/env python
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QApplication
import sys, buttonA

class Panel(QWidget):
def __init__(self):
super().__init__()

def createPanel(self):
self.a1 = buttonA.ButtonA()
self.a2 = buttonA.ButtonA()
self.v1 = self.a1.createButton()
self.v2 = self.a2.createButton()

vbox = QVBoxLayout()
vbox.addLayout(self.v1)
vbox.addLayout(self.v2)
self.setLayout(vbox)

if __name__ == "__main__":
app = QApplication(sys.argv)
p = Panel()
p.createPanel()
p.show()
sys.exit(app.exec_())

关于python - python pyqt5类引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46889571/

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