簡體   English   中英

pyqt中的世界您好嗎?

[英]Hello world in pyqt?

目前,我正在使用pycharm開發python Web應用程序。 我想用QT框架開發桌面應用程序。 我已經安裝了pyqt。 我在pyqt中搜索了hello world,並找到了這個:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        print ('Hello World')

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

但是我不知道將這段代碼放在哪里? 這是我的pyqt設計器,看起來像:
在此處輸入圖片說明

是否可以告訴我在哪里編寫代碼以及如何處理按鈕單擊?

您發布的代碼似乎是從我的答案中復制的。 該代碼是一個簡單的手寫示例,完全不需要使用Qt Designer。

使用Qt Designer的“ Hello World”示例將從以下ui文件開始:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Window</class>
 <widget class="QWidget" name="Window">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>171</width>
    <height>61</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Hello World</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <widget class="QPushButton" name="button">
     <property name="text">
      <string>Test</string>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

該文件可以另存為helloworld.ui並在Qt Designer中打開。

關於Qt Designer的第一件事是,它不是IDE,它僅用於設計GUI,而不是主程序邏輯。 程序邏輯是單獨編寫的,然后再連接到GUI。

有兩種方法可以做到這一點。 首先是使用uic模塊直接加載ui文件:

import sys, os
from PyQt4 import QtGui, QtCore, uic

DIRPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)))

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        uic.loadUi(os.path.join(DIRPATH, 'helloworld.ui'), self)
        self.button.clicked.connect(self.handleButton)

    def handleButton(self):
        print('Hello World')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

這會將GUI注入本地Window類,該子類是與Qt Designer的頂級GUI類匹配的子類(在本例中,該類也稱為“ Window”,但可以是您喜歡的任何東西)。 其他GUI窗口小部件成為該子類的屬性-因此QPushButton可用作self.button

將GUI與程序邏輯連接的另一種方法是使用pyuic工具ui文件生成python模塊:

pyuic4 --output=helloworld.py helloworld.ui

然后可以將其導入到主應用程序中:

import sys
from PyQt4 import QtGui, QtCore
from helloworld import Ui_Window

class Window(QtGui.QWidget, Ui_Window):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.button.clicked.connect(self.handleButton)

    def handleButton(self):
        print('Hello World')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

setupUi方法從生成的繼承Ui_Window類,並且不完全一樣的東西作為uic.loadUi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM