gpt4 book ai didi

python - 在 pyqt 主窗口的子对话框中配置小部件

转载 作者:行者123 更新时间:2023-12-01 05:27:18 26 4
gpt4 key购买 nike

我有一个带有主对话框的 GUI 应用程序,并向其中添加了一个按钮。按下按钮会添加另一个“对话框”,用户必须在其中输入一些值。两个 Ui 文件都是用 QTDesigner 编写的,“dialog”有一个“QtableWidget”,对象名称为“tableCo”,我不确定为什么我无法更改此 tableWidget 的属性:

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'

我必须在代码中更改哪些内容才能在子对话框中配置小部件?

最佳答案

on_Button_clicked 中的代码有两个问题。

首先,您尝试在对话框关闭后调用方法。当调用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_()

关于python - 在 pyqt 主窗口的子对话框中配置小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21066068/

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