gpt4 book ai didi

python - pyqt 中的世界你好?

转载 作者:行者123 更新时间:2023-11-28 21:21:23 24 4
gpt4 key购买 nike

目前我正在使用 pycharm 开发 python 网络应用程序。我想用 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 设计器:
enter image description here

是否可以告诉我在哪里编写代码以及如何处理按钮点击?

最佳答案

看起来您发布的代码是从 this answer 复制的我的。该代码是一个简单的手写示例,根本不涉及使用 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。

有两种方法可以做到这一点。第一种是直接加载 ui 文件,使用 uic module :

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 注入(inject)到本地 Window 类中,该类是与 Qt Designer 中的顶级 GUI 类匹配的子类(在本例中也称为“Window”,但可以是任何东西你喜欢)。其他 GUI 小部件成为子类的属性 - 因此 QPushButton 可用作 self.button

将 GUI 与程序逻辑连接起来的另一种方法是使用 pyuic toolui 文件生成 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 做的事情完全一样。

关于python - pyqt 中的世界你好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21538615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com