如何在 Python 中访问 QT 按钮(来自 UI)

How to Access a QT Button (from UI) in Python

我是QT初学者。我想创建一个简单的 GUI 来从文件加载图像。这就是为什么我在我的 GUI 中创建一个名为 pushButton 的按钮(我通过 QT Creator 设计了 ​​GUI)。现在如何从我的 python 文件访问按钮?

这是我的 XML 代码(来自 ui 文件)

<ui version="4.0">
 <class>OCR</class>
 <widget class="QWidget" name="OCR">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>567</width>
    <height>332</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>OCR</string>
  </property>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>480</x>
     <y>300</y>
     <width>75</width>
     <height>23</height>
    </rect>
   </property>
   <property name="text">
    <string>Open Image</string>
   </property>
   <property name="autoDefault">
    <bool>true</bool>
   </property>
  </widget>
  <widget class="QScrollArea" name="scrollArea">
   <property name="geometry">
    <rect>
     <x>10</x>
     <y>10</y>
     <width>541</width>
     <height>281</height>
    </rect>
   </property>
   <property name="verticalScrollBarPolicy">
    <enum>Qt::ScrollBarAlwaysOn</enum>
   </property>
   <property name="horizontalScrollBarPolicy">
    <enum>Qt::ScrollBarAlwaysOn</enum>
   </property>
   <property name="widgetResizable">
    <bool>true</bool>
   </property>
   <widget class="QWidget" name="scrollAreaWidgetContents">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>0</y>
      <width>522</width>
      <height>262</height>
     </rect>
    </property>
    <layout class="QGridLayout" name="gridLayout">
     <item row="0" column="0">
      <widget class="QLabel" name="label">
       <property name="styleSheet">
        <string notr="true">background-color: rgb(170, 255, 255);</string>
       </property>
       <property name="text">
        <string>Photo</string>
       </property>
       <property name="alignment">
        <set>Qt::AlignCenter</set>
       </property>
      </widget>
     </item>
    </layout>
   </widget>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

这是我的Python代码

import sys
import os
import cv2
from PySide2.QtGui import QImage, QPixmap

from PySide2.QtWidgets import QApplication, QWidget, QFileDialog, QPushButton
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader


class OCR(QWidget):


    def __init__(self):
        super(OCR, self).__init__()
        self.load_ui()
        self.show()
        self.image = None

    def load_ui(self):
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        loader.load(ui_file, self)
        ui_file.close()

    

if __name__ == "__main__":
    app = QApplication([])
    widget = OCR()
    widget.show()
    sys.exit(app.exec_())

在这里,load_ui 函数加载我的 UI 文件。

当你想访问按钮时,你只需在 __init__ 中使用它: self.pushButton + action

在您的代码中,您的 class(OCR) 基于 QWidget,稍后您使用 load_ui() 从文件加载此小部件。在此解决方案中,我无法访问 pushButton.

如果你想访问按钮和其他东西,我推荐稍微不同的项目结构。而是根据实际小部件制作 OCR class。

import sys
import os
from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import loadUiType

current_dir = os.path.dirname(os.path.abspath(__file__))
Form, Base = loadUiType(os.path.join(current_dir, "form.ui"))


class OCR(Base, Form):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)
        self.setupUi(self)
        self.image = None
        self.pushButton.clicked.connect(lambda: self.function_called_when_btn_is_clicked())

    def function_called_when_btn_is_clicked(self):
        print("Button clicked!!!!!!")

if __name__ == "__main__":
    app = QApplication([])
    widget = OCR()
    widget.show()
    sys.exit(app.exec_())

在此示例中,ui 文件是通过 PySide2 > loadUiType 中的函数 build 加载的。 ui 文件中的所有元素现在都可以通过 self.name_of_element__init__ 函数中访问。当您 运行 从上面编写代码时,单击按钮将导致在控制台上打印 "Button clicked!!!!!"。如果您有更多问题,请随时提问 :)

您可以先使用 self.findChild(Class, name) 注册您的按钮来访问该按钮。我已将其添加到您的代码中:

import sys
import os
import cv2
from PySide2.QtGui import QImage, QPixmap

from PySide2.QtWidgets import QApplication, QWidget, QFileDialog, QPushButton
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader


class OCR(QWidget):


    def __init__(self):
        super(OCR, self).__init__()
        self.load_ui()
        self.my_push_button = self.findChild(QPushButton, "pushButton")
        self.show()
        self.image = None

    def load_ui(self):
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        loader.load(ui_file, self)
        ui_file.close()


def print_hello_world(self):
    print("Hello world")


if __name__ == "__main__":
    app = QApplication([])
    widget = OCR()
    widget.my_push_button.clicked.connect(print_hello_world)
    widget.show()
    sys.exit(app.exec_())