Python 在pyqt主窗口的子对话框中配置小部件
我有一个带有主对话框的GUI应用程序,并在其中添加了一个按钮。 按下按钮会添加另一个“对话框”,用户必须在其中输入一些值。 这两个Ui文件都是用QTDesigner编写的,“dialog”有一个对象名为“tableCo”的“QtableWidget”。我不确定为什么不能更改此tableWidget的属性:Python 在pyqt主窗口的子对话框中配置小部件,python,pyqt,qt-designer,Python,Pyqt,Qt Designer,我有一个带有主对话框的GUI应用程序,并在其中添加了一个按钮。 按下按钮会添加另一个“对话框”,用户必须在其中输入一些值。 这两个Ui文件都是用QTDesigner编写的,“dialog”有一个对象名为“tableCo”的“QtableWidget”。我不确定为什么不能更改此tableWidget的属性: from PyQt4 import QtGui, QtCore, Qt from Main_Window import Ui_Dialog as Dlg from dialog impor
from PyQt4 import QtGui, QtCore, Qt
from Main_Window import Ui_Dialog as Dlg
from dialog import Ui_MyDialog
class MainDialog(QtGui.QDialog, Dlg):
def __init__(self):
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.connect(self.buttonOK,
QtCore.SIGNAL("clicked()"), self.onOK)
self.connect(self.buttonAbbrechen,
QtCore.SIGNAL("clicked()"), self.onClose)
self.connect(self.Button,
QtCore.SIGNAL("clicked()"), self.on_Button_clicked)
def on_Button_clicked(self, checked=None):
if checked==None: return
dialog = QtGui.QDialog()
dialog.ui = Ui_MyDialog()
dialog.ui.setupUi(dialog)
dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.exec_()
some_list=["A","B","C"]
#a list in another python class from another script that changes so
#the table properties have to be changed dynamically
#here I just take a simple list as an example
#the following two lines do not work (they work if tableCo is an
#object in the Main Dialog
self.tableCo.setColumnCount(len(some_list))
self.tableCo.setHorizontalHeaderLabels(some_list)
def onOK:
...
def onClose:
...
如果我按下按钮,我会看到我的“tableCo”小部件,但是标题的属性没有改变,在关闭这个子对话框后,我会收到以下错误消息
Traceback (most recent call last):
File "C:/gui.py", line 88, in on_Button_clicked
self.tableCo.setColumnCount(len(some_list))
AttributeError: 'MainDialog' object has no attribute 'tableCo'
要在子对话框中配置小部件,我必须在代码中更改什么?您确定
tableCo
具有确切的名称,并且它直接作为主窗口的父窗口吗?似乎没有更新属性只是因为没有self.tableCo
单击按钮时的中的代码有两个问题
首先,您试图在对话框关闭后调用方法。调用
exec时,对话框进入阻塞循环,直到用户关闭对话框。当对话框关闭时,将执行以下行,但当函数返回时,对话框将立即被垃圾回收
其次,您正试图使用self
,而不是通过本地名称dialog
,来访问对话框的方法,这就是您获得AttributeError
的原因
您可以通过为第二个对话框创建子类来解决这些问题,方法与为MainDialog
类创建子类的方法相同:
class SubDialog(QtGui.QDialog, Ui_MyDialog):
def __init__(self, some_list, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.tableCo.setColumnCount(len(some_list))
self.tableCo.setHorizontalHeaderLabels(some_list)
class MainDialog(QtGui.QDialog, Dlg):
...
def on_Button_clicked(self, checked=None):
if checked is None: return
dialog = SubQDialog(some_list)
dialog.exec_()
你能把你的代码粘贴到这里、codepad.org或其他地方吗?@user2956831。在用户进行更改并返回
dialog.exec_389;()后,您仍然可以访问其方法、属性等,因此您可以使用例如dialog.tableCo.item(0,0).text()
获取文本值,然后通过self
将其传递到主对话框。