连接来自UI文件的信号

时间:2018-10-09 07:03:39

标签: python qt-designer pyside2

在完成了一些教程之后,我设法将这个小的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的定义,并带有来自“警告”按钮的信号:

enter image description here enter image description here

我不确定registerCustomWidget()是什么,从另一个答复看来,这似乎是要做的事情。遗憾的是,official documentation无法包含circle.ui的内容。

official documentation on loading .ui files并没有显示如何与.ui文件本身中定义的项目进行交互。

如何从QDialog文件中加载完整的.ui,并获取其中的按钮以触发代码中的操作?

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>

2 个答案:

答案 0 :(得分:1)

正如我在对问题的评论中所写的那样,我找到了一个可行的解决方案。我不确定100%是否正确(至少与手动编辑.ui文件有关的部分正确),但是我看到对话框显示出来并按照我的期望进行操作。

首先,我不得不修改.ui文件中的XML,并在.py.ui文件中使用两个不同的类名。我已经将.ui中的那个修改为命名为AlertDialog,并且类型为Dialog而不是QDialog。我找不到在Qt Designer中改变类型的方法。

3,4c3,4
<  <class>Dialog</class>
<  <widget class="QDialog" name="Dialog">
---
>  <class>AlertDialog</class>
>  <widget class="Dialog" name="AlertDialog">
18c18
<     <widget class="QLineEdit" name="lineEdit"/>
---
>     <widget class="QLineEdit" name="text_field"/>
66c66
<    <receiver>Dialog</receiver>
---
>    <receiver>AlertDialog</receiver>

如您在上面看到的,输入框的名称中也有一个小错字:这就是为什么我在问题中粘贴了.ui文件的原因!)

在Python代码中,我简单地必须正确地将我的函数修饰为Slot。这是完整的代码:

from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QDialog, QMessageBox
from PySide2.QtCore import QFile, Slot
from PySide2.QtUiTools import QUiLoader

class Dialog(QDialog):
    def __init__(self, parent = None):
        super(Dialog, self).__init__(parent)

    @Slot()
    def alert(self):
        alert = QMessageBox()
        alert.setText(self.text_field.text())
        alert.exec_()


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()
    app.exec_()

整洁,不是吗?如果有人(包括我未来的自我……)知道如何摆脱.ui的调整或对该解决方案有其他改进,欢迎您提出意见!

答案 1 :(得分:0)

因为我在Pyside2上也很费劲,所以我在这里分享了如何管理它,我不确定这是最好的方法,但是对我有用。

首先,您必须安装pyqt5

pip3 install pyqt5

并假设您的文件如下:

<?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>

您只需键入命令:

pyuic5 path_to_your_ui_file -o path_to_the_output_python_file # don't forget the extension .py for the output

通常会有输出:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(344, 300)
        self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(Dialog)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.alert_button = QtWidgets.QPushButton(Dialog)
        self.alert_button.setMaximumSize(QtCore.QSize(100, 16777215))
        self.alert_button.setObjectName("alert_button")
        self.verticalLayout.addWidget(self.alert_button)
        self.quit_button = QtWidgets.QPushButton(Dialog)
        self.quit_button.setMaximumSize(QtCore.QSize(100, 16777215))
        self.quit_button.setObjectName("quit_button")
        self.verticalLayout.addWidget(self.quit_button)
        spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)

        self.retranslateUi(Dialog)
        self.alert_button.clicked.connect(Dialog.alert)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.alert_button.setText(_translate("Dialog", "Alert"))
        self.quit_button.setText(_translate("Dialog", "Quit"))

您要做的就是更正导入并加载生成的文件:

from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import QFile, QObject 
import mainwindow  # if your generated file name is mainWindow.py

class MainDialog(QDialog, mainwindow.Ui_Dialog):

    def __init__(self, parent=None):
        super(MainDialog, self).__init__(parent)
        self.setupUi(self)

app = QApplication(sys.argv)
form = MainDialog()
form.show()
app.exec_()