PyQt5开发之路(1)— PyQt5开发环境的搭建
一、前言
本次开发基于Python3.7和PyCharm,所以需要安装Python3.7环境和PyCharm;
Python3.7和PyCharm安装参考:Python的学习之路(1)— 开发环境搭建和第一个hello world程序
二、PyQt5包及其工具的安装
打开PyCharm,然后通过【Settings】 ->【Project】->【Project Interpreter】打开Python包安装界面,搜索PyQt5
,点击安装
pyqt5
安装好后,安装其工具包,搜索PyQt5-tools
,点击安装
安装成功后可以看到:
当然了直接使用pip安装也可以,后面指定的是豆瓣源。
pip install PyQt5 -i https://pypi.douban.com/simple
pip install PyQt5-tools -i https://pypi.douban.com/simple
安装好后,我们尝试运行如下python代码,可以看到,打开了一个窗口
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:William
import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
#1、创建QApplication类的实例对象
app = QApplication(sys.argv)
#2、创建一个窗口
w = QWidget()
#3、设置窗口尺寸
w.resize(600,300)
#4、移动窗口
w.move(300,300)
#5、设置窗口标题
w.setWindowTitle('第一个基于PyQT5的桌面应用')
#6、显示窗口
w.show()
#7、进入程序的主循环、并通过exit函数确保主循环安全结束
sys.exit(app.exec_())
三、工具配置
1、Qt Designer配置
点击 【Settings】->【Tools】->【External Tools】,点击加号(+)添加,
然后输入工具名称,例如我这里输入QtDesigner
,然后是使用的这个工具的可执行程序的目录,比如我的安装在D:\Program Files\Python\Python37\Lib\site-packages\qt5_applications\Qt\bin\designer.exe
,不使用参数,工作目录填为$FileDir$
即当前文件目录下,然后点击【OK】确定。
然后我们点击【Tools】->【External Tools】,选择刚才输入的工具名称QtDesigner
点击打开
然后就可以看到,【Qt Designer】已经打开了
2、PyUIC配置
这个工具的作用是把Qt的UI文件转换成.py文件。
仍然是点击添加,然后输入工具名称,例如我这里输入PyUIC
,然后是使用的这个工具的可执行程序的目录,比如我的安装在D:\Program Files\Python\Python37\Scripts\pyuic5.exe
,参数为$FileName$ -o $FileNameWithoutExtension$.py
,即将选中的文件输入为同名的.py文件,工作目录填为$FileDir$
即当前文件目录下,然后点击【OK】确定。
3、PyRcc配置
这个工具是将资源文件如图片等转成python代码能识别的文件。
点击添加,然后输入工具名称,例如我这里输入PyRcc
,然后是使用的这个工具的可执行程序的目录,比如我的安装在D:\Program Files\Python\Python37\Scripts\pyrcc5.exe
,参数为$FileName$ -o $FileNameWithoutExtension$_rc.py
,即将选中的文件输入为该文件名后加_rc
的.py文件,工作目录填为$FileDir$
即当前文件目录下,然后点击【OK】确定。
四、第一个Helloworld工程
打开QtDesigner,
选择【Main Window】,即主窗口,点击创建
然后将右侧的【Push Button】拖动过去,并输入"Hello World!
".
然后点击保存,并输入文件名
然后再PyCharm里右击,选择【PyUIC】工具,
接下来就得到了转换完成的.py文件
我们不在这个.py文件中写我们的代码,再来一个HelloRun.py
文件中,将要用到的python包及这个生成的文件导入
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
import Hello
然后通过如下代码,调用我们刚刚参加的UI界面,将其显示出来:
# 1、创建QApplication类的实例对象
app = QApplication(sys.argv)
# 2、创建一个QMainWindow主窗口实例对象
myMainWindow = QMainWindow()
# 3、创建我们自己的设计对象
myUi = Hello.Ui_MainWindow()
# 4、将我们设计的窗口加载为主窗口
myUi.setupUi(myMainWindow)
# 5、显示主窗口
myMainWindow.show()
# 6、进入程序的主循环、并通过exit函数确保主循环安全结束
sys.exit(app.exec_())
运行程序,可以看到,窗口已经打开了
其完整代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: William
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
import Hello
def main():
print("Hello world, I am William. ")
# 1、创建QApplication类的实例对象
app = QApplication(sys.argv)
# 2、创建一个QMainWindow主窗口实例对象
myMainWindow = QMainWindow()
# 3、创建我们自己的设计对象
myUi = Hello.Ui_MainWindow()
# 4、将我们设计的窗口加载为主窗口
myUi.setupUi(myMainWindow)
# 5、显示主窗口
myMainWindow.show()
# 6、进入程序的主循环、并通过exit函数确保主循环安全结束
sys.exit(app.exec_())
if __name__ == '__main__':
main()
五、解决红色波浪线的问题
我们会看到,我们导入刚才生成的.py文件时,下方会出现红色的波浪线,但不影响程序的正常运行
这里提供一个解决办法:
首先,在【Console下】的【Python Console】,勾选选项“Add source roots to PYTHONPAT
”
然后,右键当前文件夹,将其设置为【Sources Root
】
这样,红色的波浪线就消失了
六、帮助文档
我们在使用PyQt的时候如果想要知道哪些类和属性可以使用,通过使用dir()
和help()
内置函数即可;
使用dir()
函数可以用来查询一个类或者对象的所有属性,如下所示,使用dir(QWidget)
来查看QWidget对象的属性和函数:
C:\Users\william>python
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt5.QtWidgets import QWidget
>>> dir(QWidget)
['DrawChildren', 'DrawWindowBackground', 'IgnoreMask', 'PaintDeviceMetric', 'PdmDepth', 'PdmDevicePixelRatio', 'PdmDevicePixelRatioScaled', 'PdmDpiX', 'PdmDpiY', 'PdmHeight', 'PdmHeightMM', 'PdmNumColors', 'PdmPhysicalDpiX', 'PdmPhysicalDpiY', 'PdmWidth', 'PdmWidthMM', 'RenderFlag', 'RenderFlags', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'acceptDrops', 'accessibleDescription', 'accessibleName', 'actionEvent', 'actions', 'activateWindow', 'addAction', 'addActions', 'adjustSize', 'autoFillBackground', 'backgroundRole', 'baseSize', 'blockSignals', 'changeEvent', 'childAt', 'childEvent', 'children', 'childrenRect', 'childrenRegion', 'clearFocus', 'clearMask', 'close', 'closeEvent', 'colorCount', 'connectNotify', 'contentsMargins', 'contentsRect', 'contextMenuEvent', 'contextMenuPolicy', 'create', 'createWindowContainer', 'cursor', 'customContextMenuRequested', 'customEvent', 'deleteLater', 'depth', 'destroy', 'destroyed', 'devType', 'devicePixelRatio', 'devicePixelRatioF', 'devicePixelRatioFScale', 'disconnect', 'disconnectNotify', 'dragEnterEvent', 'dragLeaveEvent', 'dragMoveEvent', 'dropEvent', 'dumpObjectInfo', 'dumpObjectTree', 'dynamicPropertyNames', 'effectiveWinId', 'ensurePolished', 'enterEvent', 'event', 'eventFilter', 'find', 'findChild', 'findChildren', 'focusInEvent', 'focusNextChild', 'focusNextPrevChild', 'focusOutEvent', 'focusPolicy', 'focusPreviousChild', 'focusProxy', 'focusWidget', 'font', 'fontInfo', 'fontMetrics', 'foregroundRole', 'frameGeometry', 'frameSize', 'geometry', 'getContentsMargins', 'grab', 'grabGesture', 'grabKeyboard', 'grabMouse', 'grabShortcut', 'graphicsEffect', 'graphicsProxyWidget', 'hasFocus', 'hasHeightForWidth', 'hasMouseTracking', 'hasTabletTracking', 'height', 'heightForWidth', 'heightMM', 'hide', 'hideEvent', 'inherits', 'initPainter', 'inputMethodEvent', 'inputMethodHints', 'inputMethodQuery', 'insertAction', 'insertActions', 'installEventFilter', 'isActiveWindow', 'isAncestorOf', 'isEnabled', 'isEnabledTo', 'isFullScreen', 'isHidden', 'isLeftToRight', 'isMaximized', 'isMinimized', 'isModal', 'isRightToLeft', 'isSignalConnected', 'isVisible', 'isVisibleTo', 'isWidgetType', 'isWindow', 'isWindowModified', 'isWindowType', 'keyPressEvent', 'keyReleaseEvent', 'keyboardGrabber', 'killTimer', 'layout', 'layoutDirection', 'leaveEvent', 'locale', 'logicalDpiX', 'logicalDpiY', 'lower', 'mapFrom', 'mapFromGlobal', 'mapFromParent', 'mapTo', 'mapToGlobal', 'mapToParent', 'mask', 'maximumHeight', 'maximumSize', 'maximumWidth', 'metaObject', 'metric', 'minimumHeight', 'minimumSize', 'minimumSizeHint', 'minimumWidth', 'mouseDoubleClickEvent', 'mouseGrabber', 'mouseMoveEvent', 'mousePressEvent', 'mouseReleaseEvent', 'move', 'moveEvent', 'moveToThread', 'nativeEvent', 'nativeParentWidget', 'nextInFocusChain', 'normalGeometry', 'objectName', 'objectNameChanged', 'overrideWindowFlags', 'overrideWindowState', 'paintEngine', 'paintEvent', 'paintingActive', 'palette', 'parent', 'parentWidget', 'physicalDpiX', 'physicalDpiY', 'pos', 'previousInFocusChain', 'property', 'pyqtConfigure', 'raise_', 'receivers', 'rect', 'releaseKeyboard', 'releaseMouse', 'releaseShortcut', 'removeAction', 'removeEventFilter', 'render', 'repaint', 'resize', 'resizeEvent', 'restoreGeometry', 'saveGeometry', 'screen', 'scroll', 'sender', 'senderSignalIndex', 'setAcceptDrops', 'setAccessibleDescription', 'setAccessibleName', 'setAttribute', 'setAutoFillBackground', 'setBackgroundRole', 'setBaseSize', 'setContentsMargins', 'setContextMenuPolicy', 'setCursor', 'setDisabled', 'setEnabled', 'setFixedHeight', 'setFixedSize', 'setFixedWidth', 'setFocus', 'setFocusPolicy', 'setFocusProxy', 'setFont', 'setForegroundRole', 'setGeometry', 'setGraphicsEffect', 'setHidden', 'setInputMethodHints', 'setLayout', 'setLayoutDirection', 'setLocale', 'setMask', 'setMaximumHeight', 'setMaximumSize', 'setMaximumWidth', 'setMinimumHeight', 'setMinimumSize', 'setMinimumWidth', 'setMouseTracking', 'setObjectName', 'setPalette', 'setParent', 'setProperty', 'setShortcutAutoRepeat', 'setShortcutEnabled', 'setSizeIncrement', 'setSizePolicy', 'setStatusTip', 'setStyle', 'setStyleSheet', 'setTabOrder', 'setTabletTracking', 'setToolTip', 'setToolTipDuration', 'setUpdatesEnabled', 'setVisible', 'setWhatsThis', 'setWindowFilePath', 'setWindowFlag', 'setWindowFlags', 'setWindowIcon', 'setWindowIconText', 'setWindowModality', 'setWindowModified', 'setWindowOpacity', 'setWindowRole', 'setWindowState', 'setWindowTitle', 'sharedPainter', 'show', 'showEvent', 'showFullScreen', 'showMaximized', 'showMinimized', 'showNormal', 'signalsBlocked', 'size', 'sizeHint', 'sizeIncrement', 'sizePolicy', 'stackUnder', 'startTimer', 'staticMetaObject', 'statusTip', 'style', 'styleSheet', 'tabletEvent', 'testAttribute', 'thread', 'timerEvent', 'toolTip', 'toolTipDuration', 'tr', 'underMouse', 'ungrabGesture', 'unsetCursor', 'unsetLayoutDirection', 'unsetLocale', 'update', 'updateGeometry', 'updateMicroFocus', 'updatesEnabled', 'visibleRegion', 'whatsThis', 'wheelEvent', 'width', 'widthMM', 'winId', 'window', 'windowFilePath', 'windowFlags', 'windowHandle', 'windowIcon', 'windowIconChanged', 'windowIconText', 'windowIconTextChanged', 'windowModality', 'windowOpacity', 'windowRole', 'windowState', 'windowTitle', 'windowTitleChanged', 'windowType', 'x', 'y']
>>>
同样的,我们可以使用help(QWidget)
来参考该类的说明文档,但是在输出的帮助信息比较多的时候就不方便了,我们可以通过如下代码来将帮助信息输出为一个问价,通过文件查看。
import sys
from PyQt5.QtWidgets import QWidget
out = sys.stdout
sys.stdout = open(r'QwidgetHelp.txt', 'w')
help( QWidget )
sys.stdout.close()
sys.stdout = out
这样我们就可以在当前目录下找到QwidgetHelp.txt
文件然后查看帮助信息了
另外PyQt还提供了在线帮助文档,网址:https://www.riverbankcomputing.com/static/Docs/PyQt5/
更多信息也可以参考《PyQt5快速开发与实战》: