如何从subwindow2更新subwindow1中的组合框。以下代码应该可以正常工作,但它不会更新组合框并且不会在行显示任何错误
AddressBook().updatestock(name)
在add函数中。看起来它创建了一个AddressBook的实例。如果我怎么能纠正它。
import os
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class menudemo(QMainWindow):
def __init__(self, parent=None):
super(menudemo, self).__init__(parent)
self.pilot_widget=AddInventory()
self.drop_widget=AddressBook()
self.centralWidget=QMdiArea(self)
self.setCentralWidget(self.centralWidget)
self.sub1=QMdiSubWindow()
self.sub1.setWidget(self.drop_widget)
self.centralWidget.addSubWindow(self.sub1)
self.sub1.show()
self.sub2=QMdiSubWindow()
self.sub2.setWidget(self.pilot_widget)
self.centralWidget.addSubWindow(self.sub2)
self.sub2.show()
self.setWindowTitle("menu demo")
self.showMaximized()
class AddInventory(QWidget):
def __init__(self, parent=None):
super(AddInventory, self).__init__(parent)
self.statement=""
self.nameLabel = QLabel("Item:")
self.name=QLineEdit()
self.addButton = QPushButton("&Add")
self.addButton.setDefault(True)
self.addButton.clicked.connect(self.add)
mainLayout = QGridLayout()
mainLayout.addWidget(self.nameLabel, 0, 0)
mainLayout.addWidget(self.name,0,1)
mainLayout.addWidget(self.addButton, 0, 3)
self.setLayout(mainLayout)
self.setWindowTitle(" Address Book")
self.setFixedSize(self.sizeHint())
def add(self,text):
name=self.name.text()
AddressBook().updatestock(name)
self.name.clear()
class AddressBook(QWidget):
def __init__(self, parent=None):
super(AddressBook, self).__init__(parent)
nameLabel2 = QLabel("Item:")
self.itemstock=QComboBox(self)
self.itemstock.activated[str].connect(self.updatestock)
mainLayout = QGridLayout()
mainLayout.addWidget(nameLabel2, 0, 0)
mainLayout.addWidget(self.itemstock, 0, 1)
self.setLayout(mainLayout)
self.setWindowTitle("Simple Address Book")
self.setFixedSize(self.sizeHint())
def updatestock(self,name):
print(name)
self.itemstock.addItem(name)
def main():
app = QApplication(sys.argv)
ex = menudemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
答案 0 :(得分:1)
它不起作用,因为您只是创建AddressBook
的新实例,您可以在其上调用方法。
它未与self.drop_widget
您必须使用构造函数链接两个小部件。您可以在main
self.pilot_widget=AddInventory()
self.drop_widget=AddressBook()
我愿意:
self.drop_widget=AddressBook()
self.pilot_widget=AddInventory(self.drop_widget)
并更改AddInventory
类参数
class AddInventory(QWidget):
def __init__(self, drop_widget, parent=None):
self.drop_widget = drop_widget # now it is linked in your class as a member
现在,在add
:
def add(self,text):
name=self.name.text()
self.drop_widget.updatestock(name)
self.name.clear()