PyQt5学习教程

article/2025/9/30 19:53:06

介绍

Qt(官方发音 [kju:t],音同 cute)是一个跨平台的 C++ 开发库,主要用来开发图形用户界面(Graphical User Interface,GUI)程序,当然也可以开发不带界面的命令行(Command User Interface,CUI)程序。而PyQt5则为针对Qt开发的第三方库,使用起来很便捷。

安装

基于PyQt5的开发方式主要分为基于程序开发和基于Qt Designer开发两种。
基于Qt Designer开发不需要单独下载,anaconda就有:
在这里插入图片描述
打开pycharm->File->Setting->Tool
在这里插入图片描述
两次ok即可完成,配置完成后,pycharm中右键External Tool 打开PyQt5即可
在这里插入图片描述

转换成py文件

方法一:
命令行进入安装路径:

python -m PyQt5.uic.pyuic untitled.ui -o demo.py

在这里插入图片描述
方法二:
运行pyuic

框架

基础的PyQt5的框架

import sys
from PyQt5.QtWidgets import QApplication, QWidget
class Example(QWidget):def __init__(self):super().__init__()self.settings()def settings(self):self.setGeometry(300, 300, 450, 350)self.show()if __name__ == '__main__':app = QApplication(sys.argv)ex = Example()sys.exit(app.exec_())

基于PyQt5的demo

下面是PyQt5俄罗斯方块的代码:
原网站:http://code.py40.com/pyqt5/38.html

# -*- coding:utf-8 -*-
"""
@project: GUI_design_20220424
@author: 一阳
@time1: 2022-04-25 16:29:16
"""
import sys, random
from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication
from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt5.QtGui import QPainter, QColorclass Tetris(QMainWindow):def __init__(self):super().__init__()self.initUI()def initUI(self):self.tboard = Board(self)self.setCentralWidget(self.tboard)self.statusbar = self.statusBar()self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)self.tboard.start()self.resize(180, 380)self.center()self.setWindowTitle('Tetris')self.show()def center(self):screen = QDesktopWidget().screenGeometry()size = self.geometry()self.move((screen.width() - size.width()) / 2,(screen.height() - size.height()) / 2)class Board(QFrame):msg2Statusbar = pyqtSignal(str)BoardWidth = 10BoardHeight = 22Speed = 300def __init__(self, parent):super().__init__(parent)self.initBoard()def initBoard(self):self.timer = QBasicTimer()self.isWaitingAfterLine = Falseself.curX = 0self.curY = 0self.numLinesRemoved = 0self.board = []self.setFocusPolicy(Qt.StrongFocus)self.isStarted = Falseself.isPaused = Falseself.clearBoard()def shapeAt(self, x, y):return self.board[(y * Board.BoardWidth) + x]def setShapeAt(self, x, y, shape):self.board[(y * Board.BoardWidth) + x] = shapedef squareWidth(self):return self.contentsRect().width() // Board.BoardWidthdef squareHeight(self):return self.contentsRect().height() // Board.BoardHeightdef start(self):if self.isPaused:returnself.isStarted = Trueself.isWaitingAfterLine = Falseself.numLinesRemoved = 0self.clearBoard()self.msg2Statusbar.emit(str(self.numLinesRemoved))self.newPiece()self.timer.start(Board.Speed, self)def pause(self):if not self.isStarted:returnself.isPaused = not self.isPausedif self.isPaused:self.timer.stop()self.msg2Statusbar.emit("paused")else:self.timer.start(Board.Speed, self)self.msg2Statusbar.emit(str(self.numLinesRemoved))self.update()def paintEvent(self, event):painter = QPainter(self)rect = self.contentsRect()boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight()for i in range(Board.BoardHeight):for j in range(Board.BoardWidth):shape = self.shapeAt(j, Board.BoardHeight - i - 1)if shape != Tetrominoe.NoShape:self.drawSquare(painter,rect.left() + j * self.squareWidth(),boardTop + i * self.squareHeight(), shape)if self.curPiece.shape() != Tetrominoe.NoShape:for i in range(4):x = self.curX + self.curPiece.x(i)y = self.curY - self.curPiece.y(i)self.drawSquare(painter, rect.left() + x * self.squareWidth(),boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),self.curPiece.shape())def keyPressEvent(self, event):if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape:super(Board, self).keyPressEvent(event)returnkey = event.key()if key == Qt.Key_P:self.pause()returnif self.isPaused:returnelif key == Qt.Key_Left:self.tryMove(self.curPiece, self.curX - 1, self.curY)elif key == Qt.Key_Right:self.tryMove(self.curPiece, self.curX + 1, self.curY)elif key == Qt.Key_Down:self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY)elif key == Qt.Key_Up:self.tryMove(self.curPiece.rotateLeft(), self.curX, self.curY)elif key == Qt.Key_Space:self.dropDown()elif key == Qt.Key_D:self.oneLineDown()else:super(Board, self).keyPressEvent(event)def timerEvent(self, event):if event.timerId() == self.timer.timerId():if self.isWaitingAfterLine:self.isWaitingAfterLine = Falseself.newPiece()else:self.oneLineDown()else:super(Board, self).timerEvent(event)def clearBoard(self):for i in range(Board.BoardHeight * Board.BoardWidth):self.board.append(Tetrominoe.NoShape)def dropDown(self):newY = self.curYwhile newY > 0:if not self.tryMove(self.curPiece, self.curX, newY - 1):breaknewY -= 1self.pieceDropped()def oneLineDown(self):if not self.tryMove(self.curPiece, self.curX, self.curY - 1):self.pieceDropped()def pieceDropped(self):for i in range(4):x = self.curX + self.curPiece.x(i)y = self.curY - self.curPiece.y(i)self.setShapeAt(x, y, self.curPiece.shape())self.removeFullLines()if not self.isWaitingAfterLine:self.newPiece()def removeFullLines(self):numFullLines = 0rowsToRemove = []for i in range(Board.BoardHeight):n = 0for j in range(Board.BoardWidth):if not self.shapeAt(j, i) == Tetrominoe.NoShape:n = n + 1if n == 10:rowsToRemove.append(i)rowsToRemove.reverse()for m in rowsToRemove:for k in range(m, Board.BoardHeight):for l in range(Board.BoardWidth):self.setShapeAt(l, k, self.shapeAt(l, k + 1))numFullLines = numFullLines + len(rowsToRemove)if numFullLines > 0:self.numLinesRemoved = self.numLinesRemoved + numFullLinesself.msg2Statusbar.emit(str(self.numLinesRemoved))self.isWaitingAfterLine = Trueself.curPiece.setShape(Tetrominoe.NoShape)self.update()def newPiece(self):self.curPiece = Shape()self.curPiece.setRandomShape()self.curX = Board.BoardWidth // 2 + 1self.curY = Board.BoardHeight - 1 + self.curPiece.minY()if not self.tryMove(self.curPiece, self.curX, self.curY):self.curPiece.setShape(Tetrominoe.NoShape)self.timer.stop()self.isStarted = Falseself.msg2Statusbar.emit("Game over")def tryMove(self, newPiece, newX, newY):for i in range(4):x = newX + newPiece.x(i)y = newY - newPiece.y(i)if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:return Falseif self.shapeAt(x, y) != Tetrominoe.NoShape:return Falseself.curPiece = newPieceself.curX = newXself.curY = newYself.update()return Truedef drawSquare(self, painter, x, y, shape):colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]color = QColor(colorTable[shape])painter.fillRect(x + 1, y + 1, self.squareWidth() - 2,self.squareHeight() - 2, color)painter.setPen(color.lighter())painter.drawLine(x, y + self.squareHeight() - 1, x, y)painter.drawLine(x, y, x + self.squareWidth() - 1, y)painter.setPen(color.darker())painter.drawLine(x + 1, y + self.squareHeight() - 1,x + self.squareWidth() - 1, y + self.squareHeight() - 1)painter.drawLine(x + self.squareWidth() - 1,y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)class Tetrominoe(object):NoShape = 0ZShape = 1SShape = 2LineShape = 3TShape = 4SquareShape = 5LShape = 6MirroredLShape = 7class Shape(object):coordsTable = (((0, 0), (0, 0), (0, 0), (0, 0)),((0, -1), (0, 0), (-1, 0), (-1, 1)),((0, -1), (0, 0), (1, 0), (1, 1)),((0, -1), (0, 0), (0, 1), (0, 2)),((-1, 0), (0, 0), (1, 0), (0, 1)),((0, 0), (1, 0), (0, 1), (1, 1)),((-1, -1), (0, -1), (0, 0), (0, 1)),((1, -1), (0, -1), (0, 0), (0, 1)))def __init__(self):self.coords = [[0, 0] for i in range(4)]self.pieceShape = Tetrominoe.NoShapeself.setShape(Tetrominoe.NoShape)def shape(self):return self.pieceShapedef setShape(self, shape):table = Shape.coordsTable[shape]for i in range(4):for j in range(2):self.coords[i][j] = table[i][j]self.pieceShape = shapedef setRandomShape(self):self.setShape(random.randint(1, 7))def x(self, index):return self.coords[index][0]def y(self, index):return self.coords[index][1]def setX(self, index, x):self.coords[index][0] = xdef setY(self, index, y):self.coords[index][1] = ydef minX(self):m = self.coords[0][0]for i in range(4):m = min(m, self.coords[i][0])return mdef maxX(self):m = self.coords[0][0]for i in range(4):m = max(m, self.coords[i][0])return mdef minY(self):m = self.coords[0][1]for i in range(4):m = min(m, self.coords[i][1])return mdef maxY(self):m = self.coords[0][1]for i in range(4):m = max(m, self.coords[i][1])return mdef rotateLeft(self):if self.pieceShape == Tetrominoe.SquareShape:return selfresult = Shape()result.pieceShape = self.pieceShapefor i in range(4):result.setX(i, self.y(i))result.setY(i, -self.x(i))return resultdef rotateRight(self):if self.pieceShape == Tetrominoe.SquareShape:return selfresult = Shape()result.pieceShape = self.pieceShapefor i in range(4):result.setX(i, -self.y(i))result.setY(i, self.x(i))return resultif __name__ == '__main__':app = QApplication([])tetris = Tetris()sys.exit(app.exec_())

http://chatgpt.dhexx.cn/article/cdSI1ZWf.shtml

相关文章

PyQt完整入门教程 | 例程附代码

关注、星标公众号&#xff0c;直达精彩内容 来源&#xff1a;cnblogs 作者&#xff1a;lovesoo 1、GUI开发框架简介 pyqt是个好东西&#xff0c;可以做完整的测试方案、脚本、工具进行整合复用等等&#xff0c;本文将以一个实例和大家一起分享。先给自己挖个坑开个头&#xff0…

PyQt初级教程

PyQt5简介 这是一个PyQt5的入门教程.目的是帮助你使用PyQt5.本教程创建并在Linux上测试.PyQt4教程则覆盖了PyQt4,对应Python的2.x和3.x的Qt4的库. 原作地址&#xff1a;http://zetcode.com/gui/pyqt5/ 原翻译地址 &#xff1a;http://blog.csdn.net/neverstop_2009/article/c…

PyQt4入门教程(2)_PyQt4的第一个程序

注&#xff1a;文中译者的话将用方括号【】标出。 这一部分我们将学习PyQt中一些基本的函数。 一个简单的例子 这是一个能够显示出一个窗口的简单例子。目前为止我们已经可以对这个窗口干很多事情了&#xff0c;比如说改变它的尺寸&#xff0c;最大化&#xff0c;最小化………

一、PyQt基础知识

一、基础知识 &#xff08;一&#xff09;简介 1. 什么是PyQt5 PyQt是基于Digia公司强大的图形程序框架Qt的Python接口&#xff0c;由一组Python模块构成&#xff0c;它是一个创建GUI应用程序的工具包&#xff0c;由Phil Thompson开发。 自从1998年首次将Qt移植到Python上形…

PyQt完整入门教程

https://blog.csdn.net/baidu_37503452?spm1000.2115.3001.5343 1、GUI开发框架简介 19年来&#xff0c;一直在做Android ROM相关测试&#xff0c;也有了一定的积累&#xff1b;20年&#xff0c;计划把之前完整的测试方案、脚本、工具进行整合复用。 第一期计划是开发一个GUI的…

PyQt上手教程汇总

根据此前的PyQt学习&#xff0c;这里对PyQt的学习过程进行最后的总结 前文链接&#xff1a;由于前文标题名字取了一样的,以下内容按照前后顺序排列 (1)PyQt上手教程&#xff08;一&#xff09;_机械刘怀洋的博客-CSDN博客 (2)PyQt上手教程&#xff08;一&#xff09;_机械刘…

pyqt基础教程

PYQT是python版本的QT界面程序包&#xff0c;大家写过C、C#都做过界面设计&#xff0c;python也一样&#xff0c;非常简单。跟着我的思路走&#xff0c;五分钟学会&#xff01; 1、主体框架先造一个窗口 以下程序直接抄过去。 以下程序直接抄过去。 以下程序直接抄过去。 #!…

Mac 下安装pip,卸载pip方法

mac下直接安装pip和卸载pip的方法如下&#xff1a; 1、pip的安装&#xff1a; 输入 sudo easy_install pip 就可以安装 pip 了。 验证pip安装是否成功&#xff1a; 输入&#xff1a;pip 结果找不到文件。 尝试输入&#xff1a;pip3 -V 或者 pip3 则说明已经安装成功了。 …

pip3在Ubuntu下的安装、升级、卸载

一、参考资料 pip 常用命令 pip 官方文档 二、安装pip包 如何在 Ubuntu 20.04 上安装 Python Pip - 知乎 (zhihu.com) 1. 离线安装 Installation pip下载地址 1.1 为 Python 3 安装 pip 方式一 # 下载get-pip.py脚本 wget https://bootstrap.pypa.io/pip/3.6/get-pip.p…

conda和pip卸载包的注意事项

安装和import时包的名称不一致时&#xff0c;比如scikit-learn和sklearn&#xff08;scikit意思是科学工具箱&#xff0c;通常被缩写成sk, 比如scikit-image和skimage也是同样的情况&#xff09; 卸载的时候还是应该用包的全称&#xff0c;也就是与安装时一致用pip安装的就要用…

Python 技巧篇-pip卸载python库实例演示,查看pip命令大全方法

因为安装的 PyHook3 没安装对吧&#xff0c;有点问题&#xff0c;就想着把它卸载掉&#xff0c;然后再重新安装一个&#xff0c;那应该怎么卸载呢&#xff1f; 非常简单&#xff0c;就是 pip uninstall xxx&#xff0c;正好和我们安装时的 pip install xxx 对应&#xff0c;下…

windows下将python自带的pip卸载了,怎么重新装pip

文章目录 windows下将python自带的pip卸载了&#xff0c;怎么重新装pipLinux下将python自带的pip卸载了&#xff0c;怎么重新装pip新装Linux系统没有pip怎么装pip方法1方法2方法3总结 Linux换pip为国内镜像源|pip换源|pip修改源 windows下将python自带的pip卸载了&#xff0c;怎…

解决“更新pip版本竟将pip卸载了,提示No module named ‘pip‘”

更新pip后&#xff0c;报错无权限之类的&#xff0c;结果在运行pip发现被卸载了。 ModuleNotFoundError: No module named ‘pip’ ![在这里插入图片描述](https://img-blog.csdnimg.cn/fe4c7037709d4c7495627a706eb0ff28.png?x-oss-processimage/watermark,type_d3F5LXplbmhl…

如何使用Pip卸载软件包?

Python Pip command provides search, install, update, uninstall packages. We can use pip command to uninstall packages easily even there are some alternatives like easy_install. Python Pip命令提供搜索,安装,更新,卸载软件包。 即使有easy_install之类的替代方…

【三维点云】01-激光雷达原理与应用

文章目录 内容概要1 激光雷达原理1.1 什么是激光雷达&#xff1f;1.2 激光雷达原理1.3 激光雷达分类三角法TOF法脉冲间隔测量法幅度调制的相位测量法 相干法激光雷达用途 2 激光雷达安装、标定与同步2.1 激光雷达安装方式考虑因素 2.2 激光雷达点云用途2.3 数据融合多激光雷达数…

轻量化固态激光雷达的三维定位与建图

点云PCL免费知识星球&#xff0c;点云论文速读。 文章&#xff1a;Lightweight 3-D Localization and Mapping for Solid-State LiDAR 作者&#xff1a;Han Wang, Chen Wang, and Lihua Xie 编译&#xff1a;点云PCL 代码&#xff1a;https://github.com/wh200720041/ssl_slam.…

ROS移动机器人 Solidworks整个机器人设计文件(三维 激光雷达 arduino nvidia)(SLDPRT SLDASM)

还是17年本科时制作的毕业设计&#xff0c;基于solidworks 2014所制作。 文件里包含了制作的整个移动机器人的SolidWorks原文件。 是设计完各个零件然后组合在一起的&#xff0c;所以适用性很强&#xff0c;可以根据你的需求将绘制的零件加到你的机器人solidwroks三维中&…

Velodyne 16线三维激光雷达

Velodyne 16线三维激光雷达VLP-16介绍 16线激光雷达VLP-16是Velodyne公司出品的小型的3维激光雷达&#xff0c;保留了电机转速可调节的功能。实时上传周围距离和反射率的测量值。16线激光雷达VLP-16具有100米的远量程测量距离。精巧的外观设计使得安装非常方便。重量轻&#xf…

技术分享 | 带你探索三维激光雷达“眼中”的世界

远在火星的美国毅力号探测器早已开始工作&#xff0c;并不断的采集火星的数据传回到地球。现实中距离大众最近的无人车有谷歌的Google Driverless Car&#xff0c;以及特斯拉的model电动汽车。无人驾驶汽车正逐渐走进普通人的生活中。 毅力号火星探测器 谷歌无人汽车 提到无人驾…