【发布时间】:2025-12-24 20:50:18
【问题描述】:
按照一些教程,我设法将这个小型 Python 程序成功拉入.ui 文件并在屏幕上显示:
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QDialog, QMessageBox, QVBoxLayout
from PySide2.QtWidgets import QPushButton, QLineEdit
from PySide2.QtCore import QFile, Slot
from PySide2.QtUiTools import QUiLoader
class Dialog(QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
print('hey')
def alert(self):
print('Alert')
if __name__ == '__main__':
app = QApplication([])
loader = QUiLoader()
loader.registerCustomWidget(Dialog)
ui_file = QFile('alert-quit.ui')
ui_file.open(QFile.ReadOnly)
dialog = loader.load(ui_file)
ui_file.close()
dialog.show()
对话框正确显示,但我收到错误 QObject::connect: No such slot QDialog::alert() 并且按钮什么也不做。 (hey 文本也未显示。)
.ui 文件包含 QDialog 的定义,其中包含来自“警报”按钮的信号:
我不确定registerCustomWidget() 是什么,从另一个回复来看,这似乎是要做的事情。可悲的是,official documentation 失败了 circle.ui 包含的内容。
并且official documentation on loading .ui files 没有显示如何与.ui 文件本身中定义的项目进行交互。
如何从.ui 文件加载完整的QDialog 并获取其中的按钮以触发我的代码中的操作?
P.S.:由于我无法附加 .ui 文件,这里是它的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>344</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QPushButton" name="alert_button">
<property name="maximumSize">
<size>
<width>100</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Alert</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="quit_button">
<property name="maximumSize">
<size>
<width>100</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Quit</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>alert_button</sender>
<signal>clicked()</signal>
<receiver>Dialog</receiver>
<slot>alert()</slot>
<hints>
<hint type="sourcelabel">
<x>91</x>
<y>30</y>
</hint>
<hint type="destinationlabel">
<x>133</x>
<y>51</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<slot>alert()</slot>
<slot>quit()</slot>
</slots>
</ui>
【问题讨论】:
-
好的,我并没有停止尝试,this post,对我昨天阅读的一些帖子的回忆,帮助我走上了正轨。很快我就能回答我自己的问题了:-)
-
不,还没有。现在我可以将信号链接到 my python 类中的函数,但我仍然无法从 slot 函数引用对话框中的文本字段...任何想法?
-
您在评论中作为参考指出的问题是另一个方向。另一方面,在 PySide2 中没有执行此类任务的 loadUI 方法,其想法是实现此方法,该方法涉及解析 .ui 并获取所有元素并建立连接
-
感谢@eyllanesc 我通过稍微手动调整
.ui让它工作。我现在正在写我自己问题的答案,我会很快发布。直到.ui的调整,它看起来像一个干净的分析器......但我欢迎进一步的 cmets 和改进(最重要的是,如果我能避免.ui文件中的黑客攻击!) -
你将不得不解析文件,这就是 PyQt5 所做的,我建议你查看它以便你理解逻辑。
标签: python qt-designer pyside2