在哪里能输入代码(Pyside2)?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (180)

我在qt设计器中创建了一个ui文件,我将其转换为py文件,但我想知道在哪输入我的按钮功能

Main.py

import sys
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QFile

if __name__ == "__main__":
    app = QApplication(sys.argv)

file = QFile("mainwindow.ui")
file.open(QFile.ReadOnly)

loader = QUiLoader()
window = loader.load(file)
window.show()

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>599</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>40</x>
      <y>10</y>
      <width>231</width>
      <height>61</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>Arial Black</family>
      <pointsize>18</pointsize>
     </font>
    </property>
    <property name="text">
     <string>Press this button</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>60</x>
      <y>80</y>
      <width>181</width>
      <height>91</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>Arial Black</family>
      <pointsize>16</pointsize>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
    <property name="text">
     <string>Press</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
提问于
用户回答回答于

你需要将按钮的单击信号连接到某个功能,但为此需要知道该功能的名称,为此我们转到对象检查器:

我们看到按钮的名称是pushButton。因此,使用显示代码的main.py如下所示:

import sys
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QFile

def foo():
    print("clicked")

if __name__ == "__main__":
    app = QApplication(sys.argv)

    file = QFile("mainwindow.ui")
    if not file.open(QFile.ReadOnly):
        sys.exit(-1)

    loader = QUiLoader()
    window = loader.load(file)
    window.pushButton.clicked.connect(foo)
    window.show()

    sys.exit(app.exec_())

扫码关注云+社区

领取腾讯云代金券