Как соединить сигнальный слот (qt-designer) с функцией python - PullRequest
0 голосов
/ 04 апреля 2019

Я создал приложение с главным окном, включающим область MDI, и подокном области MDI. Оба окна создаются с помощью QT Designer и сохраняются в виде пользовательского файла. Мой скрипт Python загружает главное окно и предоставляет функцию для открытия подокна. Это работает до сих пор!

Теперь у меня есть, например, кнопка во вспомогательном окне, и она должна вызывать функцию, которая воздействует на элемент в главном окне (например, отображать текст в элементе PlainTextEdit, кроме области MDI). В Qt-Designer я могу определить сигнал и самоопределяемый слот.

pushButton -> clicked () -> MainWindow -> printText ()

Мой вопрос: Что мне нужно написать в мой код Python, чтобы перехватить сигнал в слоте "printText ()", чтобы выполнить функцию в следующем?

Я работаю с Python 3.7 и Pyside2.

Если я запускаю скрипт, в терминале отображается следующая информация:

QObject :: connect: такого слота нет QMainWindow :: printText ()

QObject :: connect: (имя отправителя: «pushButton»)

QObject :: connect: (имя получателя: 'MainWindow')

  1. Путь по умолчанию через ... self.pushButton.clicked.connect(self.function) ... не работает, потому что pushButton определен в другом классе как главное окно. (класс подокна) И я также не могу добавить этот код в класс подокна, потому что с вызываемой функцией (self.function) я не могу получить доступ к элементу в главном окне.

  2. Объявление слота (который я нашел до сих пор) в классе основного окна для перехвата сигнала также не работает:

@Slot()
def printText(self): # name of the slot

    # function which should be executed if the button is clicked
    self.ui.textOutput.setPlainText("This is a test !")

[EDIT] Если добавили код всех трех файлов. Пример содержит 2 подокна. Первый из них включен в основной файл пользовательского интерфейса (всегда активируется при выполнении). Второе подокно является независимым и может отображаться с помощью кнопки главного меню.

Файл py:

import sys

from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QMdiSubWindow, QMdiArea
from PySide2.QtCore import QFile, Slot, Signal

# Variable which contains the subwindow ID
# Required to determine if a subwindow is already open
state_limitedSubWindow = None

# Main class for loading the UI
class MyUI(QMainWindow):
    def __init__(self, ui_file, parent = None):
        super(MyUI, self).__init__(parent)

        # (1) Open UI file
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly)

        # (2) Loading UI file ...
        uiLoader = QUiLoader()
        # ... and creating an instance of the content
        self.ui = uiLoader.load(ui_file)

        # (3) Close file
        ui_file.close()

        # (4) Optional: Customize loaded UI
        # E.g. Set a window title
        self.ui.setWindowTitle("Test")

        # (5) Show the loaded and optionally customized UI
        self.ui.show()

        # A limited subwindow (only on instance can be active)
        self.ui.actionOpenSubWindow.triggered.connect(self.func_limitedSubWindow)

        @Slot()
        def printText():
            print("Debug: Inside the __init__.")

    @Slot()
    def printText(self):
        print("Debug: Inside the MainWindow class")
        self.printing()

    # Limited subwindow via action
    @Slot()
    def func_limitedSubWindow(self):

        # loading global var which contains the subwindow ID
        global state_limitedSubWindow

        if state_limitedSubWindow == None:
            limitedSubWindow = LimitedSubWindow("test_sub.ui")
            self.ui.mdiArea.addSubWindow(limitedSubWindow)
            limitedSubWindow.show()
            # Save ID of the new created subwindow in the global variable
            state_limitedSubWindow = limitedSubWindow.winId()
            # Console output subwindow ID

            print(state_limitedSubWindow)
        else:
            print("Window already exists !")

    @Slot()
    def printing(self):
        self.ui.textOutput.setPlainText("Test")

@Slot()
def printText():
    print("Debug: Outside of the class file")


# Class for the limited second window (only 1 instance can be active)
# This class can of course be in a separate py file
# The base widget of the UI file must be QWidget !!!
class LimitedSubWindow(QWidget):
    def __init__(self, ui_limitedSubWindow_file, parent = None):
        super(LimitedSubWindow, self).__init__(parent)

        # (1) Open UI file
        ui_limitedSubWindow_file = QFile(ui_limitedSubWindow_file)
        ui_limitedSubWindow_file.open(QFile.ReadOnly)

        # (2) Loading UI file ...
        ui_limitedSubWindow_Loader = QUiLoader()
        # ... and creating an instance of the content
        self.ui_limitedSubWindow = ui_limitedSubWindow_Loader.load(ui_limitedSubWindow_file, self)

        # (3) Close file
        ui_limitedSubWindow_file.close()

        self.setMinimumSize(400, 200)

        self.setWindowTitle("Limited subwindow")

        self.ui_limitedSubWindow.pushButton.clicked.connect(self.test)

    # Close event resets the variable which contains the ID
    def closeEvent(self, event):
        global state_limitedSubWindow
        # Reset the global variable
        state_limitedSubWindow = None
        event.accept()


if __name__ == "__main__":

    app = QApplication(sys.argv)

    # Creating an instance of the loading class
    frame = MyUI("test.ui")

    sys.exit(app.exec_())

Основной ui-файл:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QWidget" name="horizontalLayoutWidget">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>0</y>
      <width>791</width>
      <height>551</height>
     </rect>
    </property>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <widget class="QPlainTextEdit" name="textInput"/>
     </item>
     <item>
      <widget class="QMdiArea" name="mdiArea">
       <property name="enabled">
        <bool>true</bool>
       </property>
       <property name="maximumSize">
        <size>
         <width>517</width>
         <height>16777215</height>
        </size>
       </property>
       <widget class="QWidget" name="subwindow">
        <property name="minimumSize">
         <size>
          <width>400</width>
          <height>400</height>
         </size>
        </property>
        <property name="windowTitle">
         <string>Subwindow</string>
        </property>
        <widget class="QPushButton" name="pushButton">
         <property name="geometry">
          <rect>
           <x>160</x>
           <y>200</y>
           <width>90</width>
           <height>28</height>
          </rect>
         </property>
         <property name="text">
          <string>PushButton</string>
         </property>
        </widget>
       </widget>
      </widget>
     </item>
     <item>
      <widget class="QPlainTextEdit" name="textOutput"/>
     </item>
    </layout>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>25</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuWorkbench">
    <property name="title">
     <string>Workbench</string>
    </property>
    <addaction name="actionOpenSubWindow"/>
   </widget>
   <addaction name="menuWorkbench"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <action name="actionOpenSubWindow">
   <property name="text">
    <string>Caesar Cipher</string>
   </property>
  </action>
  <action name="actionTestText">
   <property name="text">
    <string>Test text</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>pushButton</sender>
   <signal>clicked()</signal>
   <receiver>MainWindow</receiver>
   <slot>printText()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>386</x>
     <y>263</y>
    </hint>
    <hint type="destinationlabel">
     <x>399</x>
     <y>299</y>
    </hint>
   </hints>
  </connection>
 </connections>
 <slots>
  <slot>printText()</slot>
 </slots>
</ui>

Sub ui-файл:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>315</width>
    <height>242</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>90</x>
     <y>80</y>
     <width>90</width>
     <height>28</height>
    </rect>
   </property>
   <property name="text">
    <string>PushButton</string>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

1 Ответ

0 голосов
/ 04 апреля 2019

Слот printText принадлежит классу MyUI, но слот, требующий .ui, должен принадлежать self.ui, но, к сожалению, в PySide2 использование QUiLoader не может создать класс из .ui.

Таким образом, решение состоит в том, чтобы преобразовать .ui в .py, используя pyside2-uic, поскольку он сгенерирует класс.

Принимая во внимание, что в папке находятся следующие файлы:

├── main.py
├── test_sub.ui
└── test.ui

Затем вы должны открыть терминал или CMD, расположенный в папке проекта, и выполнить:

pyside2-uic test_sub.ui -o test_sub_ui.py -x
pyside2-uic test.ui -o test_ui.py -x

Таким образом, вы должны получить следующую структуру:

.
├── main.py
├── test_sub.ui
├── test_sub_ui.py
├── test.ui
└── test_ui.py

После этого вам нужно изменить main.py (для получения дополнительной информации читайте этот предыдущий ответ ):

main.py

import sys
from PySide2 import QtCore, QtWidgets

from test_ui import Ui_MainWindow
from test_sub_ui import Ui_Form

# Variable which contains the subwindow ID
# Required to determine if a subwindow is already open
state_limitedSubWindow = None


class MyUI(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyUI, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Test")
        self.mdiArea.addSubWindow(self.subwindow)
        self.actionOpenSubWindow.triggered.connect(self.func_limitedSubWindow)

    @QtCore.Slot()
    def printText(self):
        print("Debug: Inside the MainWindow class")
        self.printing()

    @QtCore.Slot()
    def func_limitedSubWindow(self):
        # loading global var which contains the subwindow ID
        global state_limitedSubWindow
        if state_limitedSubWindow == None:
            limitedSubWindow = LimitedSubWindow()
            self.mdiArea.addSubWindow(limitedSubWindow)
            limitedSubWindow.show()
            # Save ID of the new created subwindow in the global variable
            state_limitedSubWindow = limitedSubWindow.winId()
            # Console output subwindow ID
            print(state_limitedSubWindow)
        else:
            print("Window already exists !")
        pass

    @QtCore.Slot()
    def printing(self):
        self.textOutput.setPlainText("Test")


# Class for the limited second window (only 1 instance can be active)
# This class can of course be in a separate py file
# The base widget of the UI file must be QWidget !!!
class LimitedSubWindow(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent = None):
        super(LimitedSubWindow, self).__init__(parent)
        self.setupUi(self)
        self.setMinimumSize(400, 200)
        self.setWindowTitle("Limited subwindow")

    # Close event resets the variable which contains the ID
    def closeEvent(self, event):
        global state_limitedSubWindow
        # Reset the global variable
        state_limitedSubWindow = None
        event.accept()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    # Creating an instance of the loading class
    frame = MyUI()
    frame.show()
    sys.exit(app.exec_())

Итак, в заключение, QUiLoader имеет множество ограничений, поэтому предпочтительно использовать uic.


Если вы не хотите использовать uic, тогда в предыдущем ответе я указал, как преобразовать модуль uic из PyQt5 в PySide2


Полное решение можно найти здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...