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

时间:2018-07-21 12:24:20

标签: python python-3.x pyside2

您好,我在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>

所以请您指出我可以在哪里开始编写按钮等功能,

预先感谢

1 个答案:

答案 0 :(得分:1)

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

enter image description here

我们看到按钮的名称为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_())