提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:以下是本篇文章正文内容,下面案例可供参考
————————————————
版权声明:本文为CSDN博主「dz4543」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://www.cnblogs.com/future-dream/p/12127817.html
Name: QtDesigner
Program: 选择designer.exe的目录(一般来说,在你Python安装目录下的\Lib\site-packages\pyqt5-tools\designer.exe。
安装的第三方库一般都在Lib文件夹下site-packages文件夹中。装完PyQt5,和PyQt-tools后,该目录下至少会有这俩个文件夹)。我的目录是:D:\Programs\Python\Python36\Lib\site-packages\pyqt5-tools\designer.exe,根据自己情况修改。看下图,找到它:
Arguments: $ FileName $ (复制吧,也可以自己选择insert插入,这样保证已经生成的ui文件直接用designer直接打开)
Working directory: $ FileDir $ (路径设置,同样可以直接复制,选完program后会把它当默认路径而不是工程路径,这个参数会让路径转为工程路径)
————————————————
https://blog.csdn.net/qq_43903004/article/details/113878306
此电脑 -> 属性 -> 高级 -> 系统设置 -> 环境变量
新建系统环境变量。
变量名:QT_PLUGIN_PATH
变量值:D:\Python_WorkPlace\Python3.6\Lib\site-packages\PyQt5\Qt\plugins(每个人不同)
setting》》external tools 界面 ,将 默认的working directory修改为$FileDir $即可
https://blog.csdn.net/qq_44030336/article/details/89147183
input witgets | 等待组合控件 |
---|---|
plainTextEdit | 多行文本编辑框 |
button | 按钮 |
Windowstitle | 窗体标签 |
clicked()-close()退出
QWitgie | 布局设置 |
---|---|
sicepolicy | 布局方式 |
Layout | 上下左右间距 |
spacers | 空挡 |
layoutStretch | 布局比例合计9 |
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
from 测试2 import xxxxx#导入py
import sys
if __name__ == '__main__':# 创建QApplication类的实例
app = QApplication(sys.argv)# 创建一个主窗口
mainwindow = QMainWindow() # 创建Ui_MainWindow的实例
ui =xxxxx()#函数名称#ui生成的py名称
ui.setupUi(mainwindow)# 显示窗口#动作名称
mainwindow.show()# 进入程序的主循环,并通过exit函数确保主循环安全结束
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class Fs(QMainWindow):#创建程序
def __init__(self,parent=None): #初始化
super(Fs, self).__init__(parent)#创建父类窗口
#设置标题
self.setWindowTitle('我的第一个窗口')#定义给self创建的父类窗口
self.resize(400,300)#定义尺寸
self.staus=self.statusBar()#添加状态栏
self.staus.showMessage('纯在5秒的消息',5000)#提示框
if __name__ == '__main__':#调动main,重复时不执行
app=QApplication(sys.argv)#创建一个程序
app.setWindowIcon(QIcon('img.png'))#设置图标
main=Fs()#创建一个类
main.show()#界面循环
sys.exit(app.exec_())
QMainWindow | 【主窗体】可以包含菜单栏、工具栏、状态栏和标题栏,是最常见的窗口形式 |
QDialog | 是对话窗口的基类。;没有可以包含菜单栏、工具栏、状态栏 |
QWidget | 不确定窗口的用途 |
#窗口居中
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
def initUI(self):
self.resize(250, 150)
self.setWindowTitle('center')
self.center()
self.show()
# 实现居中方式1
# def center(self):
# qr = self.frameGeometry()
# cp = QDesktopWidget().availableGeometry().center()
# qr.moveCenter(cp)
# self.move(qr.topLeft())
# // 实现居中方式2
def center(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) / 2,
(screen.height() - size.height()) / 2)
if __name__ == '__main__':
app = QApplication(sys.argv)
example = Example()
example.initUI()
sys.exit(app.exec())
# -*- coding:utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(600, 300)
self.setWindowTitle('创建按钮和按钮点击事件的例子')
self.button1 = QPushButton('按键1', self)
self.button1.clicked.connect(self.clickButton)
def clickButton(self):
sender = self.sender()
print(sender.text() + '被点击')
app=QApplication.instance()#--------------底层窗口系统接收事件
app.quit()#--------------退出程序
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import *
def ooss():
print('x= %d' % root.x())
print('y= %d' % root.y())
print('界面宽度= %d' % root.width())
print('界面高度= %d' % root.height())
app=QApplication(sys.argv)#创建程序
root=QWidget()#创建窗口
root.resize(800,500)#窗口尺寸
root.move(250,200)#移动窗口
root.setWindowTitle('屏幕数值')#窗口标题
btn=QPushButton(root)#创建按钮
btn.setText("按钮")#按钮名称
btn.move(40,80)#移动按钮
btn.clicked.connect(ooss)#信息槽
root.show()#关闭窗体
sys.exit(app.exec_())#关闭程序
#在class中只存在于图标、系统下存在系统图标
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(800,400)
self.setWindowTitle('图标')
self.setWindowIcon(QIcon('img.png'))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QToolTip, QPushButton, QApplication
from PyQt5.QtGui import QFont
class exp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
QToolTip.setFont(QFont('宋体', 10))
self.setToolTip('我是主窗体背景')
btn = QPushButton('按钮', self)
btn.setToolTip('这是一个按钮')
btn.resize(btn.sizeHint())
btn.move(40, 50)
self.setGeometry(200, 300, 400, 400)
self.setWindowTitle('按钮提示')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = exp()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import *
class Example3(QWidget):
def __init__(self):
super().__init__()
self.initUI()
pass
def initUI(self):
self.setGeometry(300, 300, 400, 400)
self.setWindowTitle('MessageBox的使用')
self.show()
pass
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message', '你确认要退出么?', QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
pass
def main5():
app = QApplication(sys.argv)
example = Example3()
sys.exit(app.exec_())
if __name__ == '__main__':
main5()
# 1.鼠标滑过label时, 会触发linkHovered
# 2.鼠标单击label时, 会触发linkActivated
import sys
from PyQt5.QtWidgets import QVBoxLayout, QApplication, QMainWindow, QLabel, QWidget
from PyQt5.QtGui import QPalette, QPixmap
from PyQt5.QtCore import Qt
class QLabelDemo(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
label1 = QLabel()
label2 = QLabel()
label3 = QLabel()
label4 = QLabel()
label1.setText("这是一个文本标签.")
label1.setAutoFillBackground(True)
patette = QPalette()
patette.setColor(QPalette.Window, Qt.blue) # 设置背景颜色
label1.setPalette(patette)
label1.setAlignment(Qt.AlignCenter)
label2.setText("欢迎使用Python GUI 程序")
label2.setAlignment(Qt.AlignCenter)
# label设置为图片展示控件
label3.setText("这是一张图片")
label3.setPixmap(QPixmap("img.png"))
label4.setOpenExternalLinks(True) # 如果设置为true,会使用浏览器打开网页 ,如果为false,则调用函数
label4.setText("这是一条连接")
label4.setAlignment(Qt.AlignRight)
label4.setToolTip("这是一个超级连接") # 添加鼠标悬于控件上边时,提示文字
# 设置垂直盒子, 装入4个label
vbox = QVBoxLayout()
vbox.addWidget(label1)
vbox.addWidget(label2)
vbox.addWidget(label3)
vbox.addWidget(label4)
label2.linkHovered.connect(self.linkHovered)
label4.linkActivated.connect(self.linkClicked)
self.setLayout(vbox)
self.setWindowTitle("QLabel控件演示")
# 鼠标滑过label时的事件
def linkHovered(self):
print("当鼠标滑过label2标签时, 触发事件")
# 鼠标点击label时的事件
def linkClicked(self):
print("当鼠标点击label4时, 触发事件")
# 入口
if __name__ == '__main__':
app = QApplication(sys.argv)
main = QLabelDemo()
main.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class DialogDemo(QMainWindow):
def __init__(self,parent=None):
super(DialogDemo, self).__init__(parent)
#设置主界面的标题及初始大小
self.setWindowTitle('Dialog例子')
self.resize(350,300)
#创建按钮,注意()内的self必不可少,用于加载自身的一些属性设置
self.btn=QPushButton(self)
#设置按钮的属性:文本,移动位置,链接槽函数
self.btn.setText('弹出对话框')
self.btn.move(50,50)
self.btn.clicked.connect(self.showdialog)
def showdialog(self):
#创建QDialog对象
dialog=QDialog()
#创建按钮到新创建的dialog对象中
btn=QPushButton('ok',dialog)
#移动按钮,设置dialog的标题
btn.move(50,50)
dialog.setWindowTitle("Dialog")
#设置窗口的属性为ApplicationModal模态,用户只有关闭弹窗后,才能关闭主界面
dialog.setWindowModality(Qt.ApplicationModal)
dialog.exec_()
if __name__ == '__main__':
app=QApplication(sys.argv)
demo=DialogDemo()
demo.show()
sys.exit(app.exec_())
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class ClipBoard(QDialog):
def __init__(self):
super(ClipBoard, self).__init__()
textCopyButton = QPushButton('复制文本')
textPasteButton = QPushButton('粘贴文本')
htmlCopyButton = QPushButton('复制HTML')
htmlPasteButton = QPushButton('粘贴HTML')
imageCopyButton = QPushButton('复制图像')
imagePasteButton = QPushButton('粘贴图像')
self.textLabel = QLabel('默认文本')
self.imageLabel = QLabel()
self.imageLabel.setPixmap(QPixmap('./images/abc.jpg'))
layout = QGridLayout()
layout.addWidget(textCopyButton,0,0)
layout.addWidget(imageCopyButton,0,1)
layout.addWidget(htmlCopyButton,0,2)
layout.addWidget(textPasteButton,1,0)
layout.addWidget(htmlPasteButton,1,1)
layout.addWidget(imagePasteButton,1,2)
layout.addWidget(self.textLabel,2,0,1,2)
layout.addWidget(self.imageLabel,2,2)
self.setLayout(layout)
textCopyButton.clicked.connect(self.copyText)
textPasteButton.clicked.connect(self.pasteText)
htmlCopyButton.clicked.connect(self.copyHtml)
htmlPasteButton.clicked.connect(self.pasteHtml)
imageCopyButton.clicked.connect(self.copyImage)
imagePasteButton.clicked.connect(self.pasteImage)
self.setWindowTitle('学习剪贴板')
def copyText(self):
clipboard = QApplication.clipboard()
clipboard.setText('hello world')
def pasteText(self):
QClipboard = QApplication.clipboard()
self.textLabel.setText(QClipboard.text())
def copyImage(self):
QClipboard = QApplication.clipboard()
QClipboard.setPixmap(QPixmap('./images/abc.jpg'))
def pasteImage(self):
QClipboard = QApplication.clipboard()
self.imageLabel.setPixmap(QClipboard.pixmap())
def copyHtml(self):
mimeData = QMimeData()
mimeData.setHtml('Bold and Red')
QClipboard = QApplication.clipboard()
QClipboard.setMimeData(mimeData)
def pasteHtml(self):
QClipboard = QApplication.clipboard()
mimeData = QClipboard.mimeData()
if QMimeData.hasHtml():
self.textLabel.setText(mimeData.html())
if __name__ == '__main__':
app = QApplication(sys.argv)
main = ClipBoard()
main.show()
sys.exit(app.exec_())
from PyQt5.QtWidgets import QPushButton, QDialog, QLabel, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QMovie
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MsgBox(QDialog):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowFlags(Qt.Tool)
self.resize(700, 545)
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) # 置顶,且去掉边框
self.setAttribute(Qt.WA_TranslucentBackground) # 窗体背景透明
self.setWindowTitle('gif图片!') # 窗口名称
label = QLabel(self)
movie = QMovie("qq1.gif") # gif文件地址
label.setMovie(movie)
movie.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
demo = MsgBox()
demo.show()
sys.exit(app.exec_())
#run
# coding:utf-8
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from cs1 import FirstMainWindow
from cs2 import Ui_Dialog1
from tt import Ui_Dialog2
from qq import Ui_Dialog5
#----------------------------------------加载ui.py
app = QtWidgets.QApplication(sys.argv)# 实例化启动qt应用
the_mainwindow = FirstMainWindow()# 取得UI class 的实例
# ----------------------------------------实例化界面
Dialog1 = QtWidgets.QDialog()
ui1 = Ui_Dialog1()# ----------------------------------------class类名
ui1.setupUi1(Dialog1)# ----------------------------------------def 名
Dialog2 = QtWidgets.QDialog()
ui2 = Ui_Dialog2()
ui2.setupUi2(Dialog2)
#
Dialog3 = QtWidgets.QDialog()
ui3 = Ui_Dialog5()
ui3.setupUi(Dialog3)
# 设计信号-槽点
# 建立对象实例化的访问
bttn = the_mainwindow.pushButton1
bttn.clicked.connect(Dialog1.show)
#
bttn2 = the_mainwindow.pushButton2
bttn2.clicked.connect(Dialog2.show)
bttn3 = the_mainwindow.pushButton3
bttn3.clicked.connect(Dialog3.show)
if __name__ == "__main__":
# 展示主窗口 chenSpider
the_mainwindow.show()
sys.exit(app.exec_())
# run
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from 翻译专属 import *
#######创建主窗口
class FirstMainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('主界面')
###### 创建界面 ######
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.Layout = QVBoxLayout(self.centralwidget)
# 设置顶部按钮
self.topwidget = QWidget()
self.Layout.addWidget(self.topwidget)
self.buttonLayout = QHBoxLayout(self.topwidget)
self.pushButton1 = QPushButton()
self.pushButton1.setText("打开主界面")
self.buttonLayout.addWidget(self.pushButton1)
self.pushButton2 = QPushButton()
self.pushButton2.setText("打开主翻译")
self.buttonLayout.addWidget(self.pushButton2)
###### 按钮事件 ######
self.pushButton1.clicked.connect(self.on_pushButton1_clicked)
self.pushButton2.clicked.connect(self.on_pushButton1_clicked1)
# 按钮一:打开主界面
windowList = []
def on_pushButton1_clicked(self):
the_window =SecondWindow()
self.windowList.append(the_window) ##注:没有这句,是不打开另一个主界面的!
# self.close()
the_window.show()
windowList = []
def on_pushButton1_clicked1(self):
the_window =windApp()
self.windowList.append(the_window) ##注:没有这句,是不打开另一个主界面的!
# self.close()
the_window.show()
######第二个主界面
###############################################
class SecondWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('第二主界面')
# 设置中间文本
self.label = QLabel()
self.label.setText("第二个主界面")
self.label.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
self.label.setAlignment(Qt.AlignCenter)
self.label.setFont(QFont("Roman times", 50, QFont.Bold))
self.setCentralWidget(self.label)
###########
if __name__ == "__main__":
app = QApplication(sys.argv)
the_mainwindow = FirstMainWindow()
the_mainwindow.show()
sys.exit(app.exec_())
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import math
class sssa(QWidget):
def __init__(self):
super(sssa, self).__init__()
self.resize(600,600)
self.setWindowTitle('直线')
def paintEvent(self,event):#自动脚本子程序
self.text='我是python'
pat=QPainter(self)
pat.begin(self)#初始化
pen=QPen(Qt.red,3,Qt.SolidLine)#直线
pat.setPen(pen)
pat.drawLine(20,40,250,40)
pen.setStyle(Qt.DashLine)#虚线
pat.setPen(pen)
pat.drawLine(20, 80, 250, 80)
pen.setStyle(Qt.DashDotDotLine)#虚点线
pat.setPen(pen)
pat.drawLine(20, 120, 250, 120)
pen.setStyle(Qt.DotLine) # 虚点线
pat.setPen(pen)
pat.drawLine(20, 160, 250, 160)
pen.setStyle(Qt.DashDotDotLine) # 虚点线
pat.setPen(pen)
pat.drawLine(20, 180, 250, 180)
pen.setStyle(Qt.CustomDashLine) # 虚点线
pen.setDashPattern([1,4,5,4])
pat.setPen(pen)
pat.drawLine(20, 200, 250, 200)
#文字中心
pat.setPen(QColor(150,43,5))
pat.setFont(QFont('SimSun',25))
pat.drawText(event.rect(),Qt.AlignCenter,self.text)
#曲线
size = self.size()
for i in range(1000):
x = 100 * (-1 + 2.0 * i / 1000) + size.width() / 2.0
# T = 50
y = -50 * math.sin((x - size.width() / 2.0) * math.pi / 50) + size.height() / 2.0
pat.drawPoint(int(x), int(y))
size = self.size()
#2/1半圆
pat.setPen(Qt.blue)
rect=QRect(200,10,100,100)
pat.drawArc(rect,0,50 * 16)
#红色圆
pat.setPen(Qt.red)
pat.drawArc(350,10,100,100,0,360 * 16)
#红色圆带旋
pat.drawChord(450,10,100,100,12,130*16)
#扇形
pat.drawPie(450,100,100,100,12,130*16)
#椭圆
pat.drawEllipse(250,120,150,100)
#正五边形
pt1=QPoint(450,150)
pt2 = QPoint(500, 200)
pt3 = QPoint(450, 250)
pt4 = QPoint(350, 250)
pt5 = QPoint(350, 150)
polygon=QPolygon([pt1,pt2,pt3,pt4,pt5])
pat.drawPolygon(polygon)
#图片
imge=QImage('img.png')
rect=QRect(10,300,int(imge.width()/1.5),int(imge.height()/1.5))
pat.drawImage(rect,imge)
#填充区域纯黑
br=QBrush(Qt.SolidPattern)
pat.setBrush(br)
pat.drawRect(10,450,90,60)
# 填充区域点黑
br = QBrush(Qt.Dense1Pattern)
pat.setBrush(br)
pat.drawRect(150,450, 90, 60)
# 填充区域点黑
br = QBrush(Qt.Dense2Pattern)
pat.setBrush(br)
pat.drawRect(300, 450, 90, 60)
# 填充区域点黑
br = QBrush(Qt.Dense3Pattern)
pat.setBrush(br)
pat.drawRect(450, 450, 90, 60)
pat.end()#结束
#
if __name__ == '__main__':
app = QApplication(sys.argv)
main = sssa() # 这里设置图标可以生成应用程序图标
main.show()
sys.exit(app.exec_())
#登录窗口ui转py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dengl.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(387, 173)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(100, 30, 113, 20))
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(80, 100, 75, 23))
self.pushButton.setObjectName("pushButton")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(100, 70, 113, 20))
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(160, 100, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(30, 30, 54, 12))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(40, 70, 54, 12))
self.label_2.setObjectName("label_2")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 387, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "登录窗口"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton_2.setText(_translate("MainWindow", "PushButton"))
self.label.setText(_translate("MainWindow", "TextLabel"))
self.label_2.setText(_translate("MainWindow", "TextLabel"))
#登录窗口背景透明化图标
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from dengl import Ui_MainWindow # ui 使用 Qt designer 创建
```python
class MyWindown(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setWindowTitle("账号登陆") # 设置标题
self.setWindowIcon(QIcon("img.png")) # 添加图标
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) # 置顶,且去掉边框
self.setAttribute(Qt.WA_TranslucentBackground) # 窗体背景透明
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWindown()
w.show()
sys.exit(app.exec())
```python
import sys
from PyQt5.QtWidgets import *
class Example3(QWidget):
def __init__(self):
super().__init__()
self.initUI()
pass
def initUI(self):
self.setGeometry(300, 300, 400, 400)
self.setWindowTitle('MessageBox的使用')
self.show()
pass
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message', '你确认要退出么?', QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
pass
def main5():
app = QApplication(sys.argv)
example = Example3()
sys.exit(app.exec_())
if __name__ == '__main__':
main5()
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。
import sys
import time
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import os
# from 主程序.py.翻译专属 import windApp
# from 主程序.py.ui.translate import Ui_MainWindow
import math
from PyQt5 import QtPrintSupport,QtGui
from PyQt5.QtPrintSupport import *
class Zzck(QMainWindow):
def __init__(self):
super(Zzck, self).__init__()
self.iniUI()
# 主界面布局
def iniUI(self): # 主窗体布局
self.setWindowTitle("我是主窗体")
self.resize(800, 400) #
# self.getGeometry(400, 400, 400, 400)
# 提示信息
self.ts = self.statusBar() # 创建提示功能
self.ts.showMessage("存在5秒消息", 5000)
# 提示信息及局中-sub
self.cetan() # 局中
QToolTip.setFont(QFont("宋体", 12))
self.setToolTip('今天是星期五')
# self.setGeometry(100,100,200,300)
# 退出用用程序按钮button
self.button = QPushButton()
self.button.setText('退出用用程序按')
self.button.clicked.connect(self.on_exit)
# 坐标信息
self.button1 = QPushButton()
self.button1.setText("我是坐标按钮")
self.button1.setToolTip('我是一个提示信息')
self.button1.clicked.connect(self.on_xx1) # 信息槽
# 布局按钮
# 退出用用程序按钮button-布局
# label布局----------------------------------------------------------------------
self.label1 = QLabel(self) # 创建 label 实例
self.label2 = QLabel(self)
label3 = QLabel(self)
label4 = QLabel(self)
# 1
self.label1.setText("这是一个文本标签。") # lable11 添加文字
self.label1.setAutoFillBackground(True)
palette = QPalette() # 创建调色板类实例
palette.setColor(QPalette.Window, Qt.red) # 设置为蓝色
self.label1.setPalette(palette)
self.label1.setAlignment(Qt.AlignCenter) # 设置居中
# 创建滑动块
self.hdk=QSlider(Qt.Horizontal)#创建滑动块(Qt.Vertical)--垂直按钮
self.hdk.setMaximum(25)#最大值
self.hdk.setMinimum(10)#最小值
self.hdk.setSingleStep(1)#步长
self.hdk.setValue(15)#当前值
self.hdk.setTickPosition(QSlider.TicksBelow)#刻度在下方
self.hdk.setTickInterval(1)#设置刻度间隔
self.hdk.valueChanged.connect(self.hdk_1)
#字体切换
self.xzzt = QPushButton('选择字体')
self.xzzt.clicked.connect(self.get_zt)
self.bjys = QPushButton('设置字体颜色')
self.bjys.clicked.connect(self.get_zt1)
self.ztys = QPushButton('设置背景颜色')
self.ztys.clicked.connect(self.get_zt2)
#添加字体大小滑动按钮
self.label2.setText("欢迎使用Python GUI 应用")
label3.setAlignment(Qt.AlignCenter)
label3.setToolTip('这是一个图片标签') # 设置鼠标移动上的一个提示语
label3.setPixmap(QPixmap("img.png")) # 设置 lab12为 图片
label4.setText("欢迎访问百度")
label4.setAlignment(Qt.AlignRight)
label4.setToolTip('这是一个超链接标签')
xzzy = QHBoxLayout() # 字体设置
xzzy.addWidget(self.xzzt)
xzzy.addWidget(self.bjys)
xzzy.addWidget(self.ztys)
# 2
vbox = QVBoxLayout() # 创建一个layout
vbox.addWidget(self.label1) # layout中添加 组件
vbox.addLayout(xzzy)
vbox.addStretch() # 按照比例 分配大小
vbox.addWidget(self.hdk)
vbox.addWidget(self.label2)
vbox.addStretch()
vbox.addWidget(label3)
vbox.addStretch()
vbox.addWidget(label4)
# 3
self.label1.setOpenExternalLinks(True)
# 打开允许访问超链接,默认是不允许,需要使用 setOpenExternalLinks(True)允许浏览器访问超链接
label4.setOpenExternalLinks(False) # 如果改成 True 点击就会访问 链接的网址
# 点击文本框绑定槽事件
def link_clicked():
print("sadf")
label4.linkActivated.connect(link_clicked)
# 划过文本框绑定槽事件
def link_hovered():
print("sadf")
self.label2.linkHovered.connect(link_hovered)
self.label1.setTextInteractionFlags(Qt.TextSelectableByMouse)
# QLineEdit样式--------------------------------------------------
form = QFormLayout() # 表单布局
ed1 = QLineEdit()
ed2 = QLineEdit()
ed3 = QLineEdit()
ed4 = QLineEdit()
form.addRow("Norml", ed1)
form.addRow("NoEcho", ed2)
form.addRow("Password", ed3)
form.addRow("PasswordEchoOnEdit", ed4)
#提示信息
ed1.setPlaceholderText("正常输入")
ed2.setPlaceholderText("回显")
ed3.setPlaceholderText("密码")
ed4.setPlaceholderText("密码半显")
ed1.setEchoMode(QLineEdit.Normal)
ed2.setEchoMode(QLineEdit.NoEcho)
ed3.setEchoMode(QLineEdit.Password)
ed4.setEchoMode(QLineEdit.PasswordEchoOnEdit)
# QLineEdit效验--------------------------------------------------
ed5= QLineEdit()
ed6 = QLineEdit()
ed7 = QLineEdit()
form.addRow("整数", ed5)
form.addRow("浮点", ed6)
form.addRow("数值", ed7)
# 提示信息
ed5.setPlaceholderText("输入整数[1-99]")
ed6.setPlaceholderText("输入浮点数[-999.99~999.99]")
ed7.setPlaceholderText("数值a-A,0-9")
#整数效应器
xde5=QIntValidator(self)
xde5.setRange(1,99)
# 浮点数效应器
xed6=QDoubleValidator(self)
xed6.setRange(-360,360)
xed6.setNotation(QDoubleValidator.StandardNotation)
#两位小数
xed6.setDecimals(2)
# 数值效应器
reg=QRegExp('[a-zA-z0-9]+$')
xe7=QRegExpValidator(self)
xe7.setRegExp(reg)
#设置效应器
ed5.setValidator(xde5)
ed6.setValidator(xed6)
ed7.setValidator(xe7)
# 遮荫马输入
ed8 = QLineEdit()
ed9 = QLineEdit()
ed10 = QLineEdit()
ed11 = QLineEdit()
ed8.setInputMask('000.000.000.000;_')
ed9.setInputMask('HH:HH:HH:HH;_')
ed10.setInputMask('0000-00-00')
ed11.setInputMask('>AAAAA-AAAAA-AAAAA;#')
form.addRow('数字遮掩',ed8)
form.addRow('Mac遮掩', ed9)
form.addRow('日期遮掩', ed10)
form.addRow('许可证遮掩', ed11)
# 长度、文本变化、只读
ed12 = QLineEdit()
ed13 = QLineEdit()
ed14 = QLineEdit('我是不可编辑文本')
ed12.setValidator(QIntValidator())
ed12.setMaxLength(4)#长度不大于4
ed12.setAlignment(Qt.AlignRight)#右侧输入
ed12.setFont(QFont('宋体',20))
ed12.setPlaceholderText("字体20;限制4位数值")
ed13.textChanged.connect(self.on_bh)
ed14.setReadOnly(True)
form.addRow("右侧输入:",ed12)
form.addRow("文本变化:", ed13)
form.addRow("我不渴编辑:", ed14)
# 多行文本
self.ded1=QTextEdit()
button3=QPushButton('显示文本')
button4 = QPushButton('改文本样式')
button5 = QPushButton('获取显示文本')
button6 = QPushButton('获取该文本样式')
#信息操
button3.clicked.connect(self.on_b3)
button4.clicked.connect(self.on_b4)
button5.clicked.connect(self.on_b5)
button6.clicked.connect(self.on_b6)
#属相布局
sxla=QVBoxLayout()
sxla.addWidget(self.ded1)
sxla.addWidget(button3)
sxla.addWidget(button4)
sxla.addWidget(button5)
sxla.addWidget(button6)
#调用本参数名称\
self.button7=QPushButton()
self.button7.setText('我是开关按钮')
self.button7.setCheckable(True)
self.button7.toggle()
#位置调用开光反向
self.button7.clicked.connect(lambda: self.kg_an(self.button7))
self.button7.clicked.connect(self.kg_an1)
# 调用图像按钮
self.button8 = QPushButton()
self.button8.setText('图像按钮1')
self.button8.setIcon(QIcon(QPixmap('img.png')))
self.button8.clicked.connect(lambda: self.kg_an(self.button8))
button9 = QPushButton()
button9.setText('不可用按钮1')
button9.setEnabled(False)
#只能由一个默认按钮
self.button10 = QPushButton('&默认按钮')
self.button10.setDefault(True)
self.button8.clicked.connect(lambda: self.kg_an(self.button10))
#单选按钮
self.rad1=QRadioButton('单选按钮1')
self.rad1.setChecked(True)
self.rad1.toggled.connect(self.rad_an)
self.rad2 = QRadioButton('单选按钮2')
self.rad2.toggled.connect(self.rad_an)
self.rad2.toggled.connect(self.rad_an)
#复选框按钮
self.fxk1=QCheckBox('复选框1')
self.fxk1.setChecked(True)
# self.fxk1.stateChanged.connect(lambda: self.xk_an(self.fxk1))
self.fxk2 = QCheckBox('复选框2')
# self.fxk2.stateChanged.connect(lambda: self.xk_an(self.fxk2))
self.fxk3 = QCheckBox('半选中')
# self.fxk3.stateChanged.connect(lambda: self.xk_an(self.fxk3))
self.fxk3.setTristate(True)
self.fxk3.setCheckState(Qt.PartiallyChecked)
#下拉列表---addItems加入字典-----------
self.la1=QLabel('选择学习语言')
self.cd=QComboBox()
self.cd.addItem('c++')
self.cd.addItem('python')
self.cd.addItem('Java')
self.cd.addItems(['c#','JS','VB'])
self.cd.currentIndexChanged.connect(self.cd_an)
vbox.addWidget(self.la1)
vbox.addWidget(self.cd)
#计数器控件
self.la2 = QLabel() # 显示框
self.sb=QSpinBox()#创建计数器
self.sb.setValue(15)
self.sb.setRange(10,30)#最大和最小值
self.sb.valueChanged.connect(self.sb_sub1)
#对话框
self.button11=QPushButton('提示框QWidget')
self.button11.clicked.connect(self.showQW)
# 另类对话框
self.button15 = QPushButton('关于对话框')
self.button15.clicked.connect(self.showQW1)
self.button16 = QPushButton('消息对话框')
self.button16.clicked.connect(self.showQW1)
self.button17 = QPushButton('警告对话框')
self.button17.clicked.connect(self.showQW1)
self.button18 = QPushButton('错误对话框')
self.button18.clicked.connect(self.showQW1)
self.button19 = QPushButton('提问对话框')
self.button19.clicked.connect(self.showQW1)
#弹出消息获取内容
self.button20= QPushButton('获取列表')
self.dit=QLineEdit()
self.button20.clicked.connect(self.getlb)
self.button21 = QPushButton('获取输入')
self.dit1 = QLineEdit()
self.button21.clicked.connect(self.getwz)
self.button22 = QPushButton('获取整值')
self.dit2 = QLineEdit()
self.button22.clicked.connect(self.getzs)
self.button25=QPushButton('窗口绘制按钮')
self.button25.clicked.connect(self.ckhz)
self.button26=QPushButton('日历')
self.button26.clicked.connect(self.rl)
#创建使用菜单栏
bar=self.menuBar()
file=bar.addMenu('文件')
file.addAction('show')
sava=QAction('保存',self)
sava.setShortcut("Ctrl+S")
file.addAction(sava)
que = QAction("退出", self)
file.addAction(que)
ed1=bar.addMenu("编辑")#ed1=file.addMenu()时候分割
ed1.addAction("复制")
ed1.addAction('粘贴')
sava.triggered.connect(self.ppo)
# 状态栏
file.triggered.connect(self.oop)
self.setCentralWidget(QTextEdit())
self.statusBar = QStatusBar()
self.setStatusBar(self.statusBar)
#工具栏
tb1=self.addToolBar("File")
ne1=QAction(QIcon('img.png'),'新建',self)
tb1.addAction(ne1)
ne2 = QAction(QIcon('img_1.png'), '微信', self)
tb1.addAction(ne2)
ne3 = QAction(QIcon('img_2.png'), 'QQ', self)
tb1.addAction(ne3)
#图片加文字下方
tb1.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
#安下工具1
tb1.actionTriggered.connect(self.on_ss)
tb2 = self.addToolBar("File")
ne2 = QAction(QIcon('img.png'), '新建', self)
tb2.addAction(ne2)
#安下工具2
tb2.actionTriggered.connect(self.on_ss)
#打印功能
self.button28=QPushButton("打印功能")
self.button28.clicked.connect(self.on_28)
#excel模型
self.button29=QPushButton("表格功能")
self.button29.clicked.connect(self.on_29)
# 树菜单
self.button30 = QPushButton("树菜单窗口")
self.button30.clicked.connect(self.on_30)
#树菜单
# 树菜单
self.button31 = QPushButton("树菜单添加")
self.button31.clicked.connect(self.on_31)
#多线程显示时间
self.button32 = QPushButton("多线程显示时间")
self.button32.clicked.connect(self.on_32)
# label布局----------------------------------------------------------------------
#表布局
bla=QFormLayout()
bla.addRow(self.button20, self.dit)
bla.addRow(self.button21, self.dit1)
bla.addRow(self.button22, self.dit2)
#计数器区域
jsxla=QHBoxLayout()
jsxla.addWidget(self.la2)
jsxla.addWidget(self.sb)
#提示按钮
xlad=QHBoxLayout()
xlad.addWidget(self.button11)
xlad.addWidget(self.button15)
xlad.addWidget(self.button16)
xlad.addWidget(self.button17)
xlad.addWidget(self.button18)
xlad.addWidget(self.button19)
#第三行按钮
xlad3 = QHBoxLayout()
xlad3.addWidget(self.button25)
xlad3.addWidget(self.button26)
xlad3.addWidget(self.button28)
xlad3.addWidget(self.button29)
xlad3.addWidget(self.button30)
xlad3.addWidget(self.button31)
xlad3.addWidget(self.button32)
#单选按钮区域
dxla=QHBoxLayout()
dxla.addWidget(self.rad1)
dxla.addWidget(self.rad2)
#复选框
# 单选按钮区域
fxkxla = QHBoxLayout()
fxkxla.addWidget(self.fxk1)
fxkxla.addWidget(self.fxk2)
fxkxla.addWidget(self.fxk3)
#区域2-2\label下方
vbox1=QVBoxLayout()
vbox1.addLayout(vbox)
vbox1.addLayout(xzzy)
vbox1.addLayout(bla)
vbox1.addLayout(jsxla)
vbox1.addLayout(dxla)
vbox1.addLayout(fxkxla)
#区域下1按钮
yla = QHBoxLayout()
yla.addWidget(self.button)
yla.addWidget(self.button1)
yla.addWidget(self.button7)
yla.addWidget(self.button8)
yla.addWidget(button9)
yla.addWidget(self.button10)
#区域2
qy1 = QHBoxLayout() # 区域1
qy1.addLayout(form)
# qy1.addStretch(0)#增加缩进
qy1.addLayout(vbox1)
qy1.addLayout(sxla)
#布局比例
qy1.setStretch(0, 1)
qy1.setStretch(1, 1)
# 区域2
# 全局布局
alllayout = QVBoxLayout() # 创建全局布局
alllayout.addLayout(qy1) # 将布局方式加入全局布局
alllayout.addLayout(yla) # 将布局方式加入全局布局
alllayout.addLayout(xlad)
alllayout.addLayout(xlad3)
widget = QWidget() # 创建窗口
widget.setLayout(alllayout) # 窗口设为全局布局
self.setCentralWidget(widget)
#多线程显示时间
def on_32(self):
self.ddsa=ThreadUpdateUI()
self.ddsa.show()
#树菜单添加
def on_31(self):
dia6=QDialog()
dia6.resize(400,600)
operatorLayout = QHBoxLayout() # 水平布局
addBtn = QPushButton('添加节点')
updateBtn = QPushButton('修改节点')
deleteBtn = QPushButton('删除节点')
operatorLayout.addWidget(addBtn)
operatorLayout.addWidget(updateBtn)
operatorLayout.addWidget(deleteBtn)
addBtn.clicked.connect(self.addNode)
updateBtn.clicked.connect(self.updateNode)
deleteBtn.clicked.connect(self.deleteNode)
# 树
self.tree = QTreeWidget()
# 为树控件指定列数
self.tree.setColumnCount(2)
# 指定列标签
self.tree.setHeaderLabels(['Key', 'Value'])
# 根节点
root = QTreeWidgetItem(self.tree)
root.setText(0, 'root') # 0代表第一列,即Key列,值为root
root.setText(1, '0')
# 添加子节点child1
child1 = QTreeWidgetItem(root)
child1.setText(0, 'child1')
child1.setText(1, '1')
# 添加子节点child2
child2 = QTreeWidgetItem(root)
child2.setText(0, 'child2')
child2.setText(1, '2')
# 为child2添加一个子节点child3
child3 = QTreeWidgetItem(child2)
child3.setText(0, 'child3')
child3.setText(1, '3')
# 信号和槽
self.tree.clicked.connect(self.onTreeClicked)
mainLayout = QVBoxLayout(self)
mainLayout.addLayout(operatorLayout)
mainLayout.addWidget(self.tree)
dia6.setLayout(mainLayout)
dia6.exec_()
def onTreeClicked(self, index): # index是被点击节点的索引
item = self.tree.currentItem() # 获得当前单击项
print('当前处于第%d行' % index.row()) # 输出当前行(自己父节点的第几个值)
print('key=%s,value=%s' % (item.text(0), item.text(1)))
print()
def addNode(self):
print('添加节点')
item = self.tree.currentItem() # 获得当前结点
print('当前节点是:', item)
node = QTreeWidgetItem(item)
node.setText(0, '新节点')
node.setText(1, '新值')
def updateNode(self):
print('修改节点')
item = self.tree.currentItem()
item.setText(0, '修改节点')
item.setText(1, '值已经被修改')
def deleteNode(self):
print('删除节点')
# 防止item是root时,root无父结点报错,要使用下面的写法
rootFather = self.tree.invisibleRootItem() # 获得根节点root的不可见的父节点
for item in self.tree.selectedItems():
# 父节点不为空
(item.parent() or rootFather).removeChild(item)
#树菜单
def on_30(self):
dia5=QDialog()
dia5.resize(600,600)
hbox = QHBoxLayout(dia5)
left = QFrame(dia5)
# QFrame 控件添加StyledPanel样式能使QFrame 控件之间的界限更加明显
# left.setFrameShape(QFrame.StyledPanel)
right = QFrame(dia5)
# right.setFrameShape(QFrame.StyledPanel)
splitter1 = QSplitter(Qt.Horizontal)
splitter1.addWidget(left)
splitter1.setSizes([20, ]) # 设置分隔条位置
splitter1.addWidget(right)
hbox.addWidget(splitter1)
self.setLayout(hbox)
# 树
self.tree = QTreeWidget(left)
self.tree.setStyleSheet("background-color:#eeeeee;border:outset;color:#215b63;")
self.tree.setAutoScroll(True)
self.tree.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed)
self.tree.setTextElideMode(Qt.ElideMiddle)
# self.tree.setIndentation(30)
self.tree.setRootIsDecorated(True)
self.tree.setUniformRowHeights(False)
self.tree.setItemsExpandable(True)
self.tree.setAnimated(False)
self.tree.setHeaderHidden(True)
self.tree.setExpandsOnDoubleClick(True)
self.tree.setObjectName("tree")
# 设置根节点
root = QTreeWidgetItem(self.tree)
root.setText(0, '系统管理')
# 设置树形控件的列的宽度
# self.tree.setColumnWidth(0, 150)
# 设置子节点1
child1 = QTreeWidgetItem()
child1.setText(0, '增加人员信息')
root.addChild(child1)
# 设置子节点2
child2 = QTreeWidgetItem(root)
child2.setText(0, '查询人员信息')
# 加载根节点的所有属性与子控件
self.tree.addTopLevelItem(root)
# 设置stackedWidget
self.stackedWidget = QStackedWidget(right)
# 设置第一个面板
self.form1 = QWidget()
self.formLayout1 = QHBoxLayout(self.form1)
self.label1 = QLabel()
self.label1.setText("增加人员信息面板")
self.label1.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
self.label1.setAlignment(Qt.AlignCenter)
self.label1.setFont(QFont("Roman times", 50, QFont.Bold))
self.formLayout1.addWidget(self.label1)
# 设置第二个面板
self.form2 = QWidget()
self.formLayout2 = QHBoxLayout(self.form2)
self.label2 = QLabel()
self.label2.setText("查询人员信息面板")
self.label2.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
self.label2.setAlignment(Qt.AlignCenter)
self.label2.setFont(QFont("Roman times", 50, QFont.Bold))
self.formLayout2.addWidget(self.label2)
# 将两个面板,加入stackedWidget
self.stackedWidget.addWidget(self.form1)
self.stackedWidget.addWidget(self.form2)
# 树节点监听事件
self.tree.clicked.connect(self.onClicked)
# 窗口最大化
dia5.setWindowTitle('树窗口分隔案列')
dia5.show()
dia5.exec_()
def onClicked(self, qmodeLindex):
item = self.tree.currentItem()
print('Key=%s,value=%s' % (item.text(0), item.text(1)))
if item.text(0) == '增加人员信息':
self.on_pushButton1_clicked()
elif item.text(0) == '查询人员信息':
self.on_pushButton2_clicked()
else:
print('返回主界面')
# 按钮一:打开第一个面板
def on_pushButton1_clicked(self):
self.stackedWidget.setCurrentIndex(0)
# 按钮二:打开第二个面板
def on_pushButton2_clicked(self):
self.stackedWidget.setCurrentIndex(1)
#表格
def on_29(self):
dia3=QDialog()
dia3.resize(500,800)
self.modaa = QStandardItemModel(50, 3) # 创建模型
self.modaa.setHorizontalHeaderLabels(['id', '姓名', 'age'])
self.tab = QTableView() # 创建表
self.tab.setModel(self.modaa)
t0_0 = QStandardItem("001")
t0_1 = QStandardItem("局中布局")
t0_1.setTextAlignment(Qt.AlignCenter | Qt.AlignBottom)
t0_2 = QStandardItem("局中上")
t0_2.setTextAlignment(Qt.AlignRight )
self.modaa.setItem(0, 0, t0_0)
self.modaa.setItem(0, 1, t0_1)
self.modaa.setItem(0, 2, t0_2)
#合并单元格
Item1 = QStandardItem('老王')
# 设置单元格对齐方式:常量在Qt中
Item1.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
self.modaa.setItem(2, 0, Item1)
# self.modaa.setSpan(2, 0, 2, 1)
#只支持 Item1 = QTableWidgetItem('老王')
#字体和颜色
t0_0 = QStandardItem("雷神")
t0_0.setFont(QFont('Times',20,QFont.Black))
t0_0.setForeground(QBrush(QColor(255,0,0)))
t0_1 = QStandardItem("h二维ks")
t0_1.setForeground(QBrush(QColor(255, 255, 0)))
t0_1.setBackground(QBrush(QColor(0, 0, 225)))
#右对齐
t0_2 = QStandardItem("右下角")
#右下角
t0_2.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
self.modaa.setItem(1, 0, t0_0)
self.modaa.setItem(1, 1, t0_1)
self.modaa.setItem(1, 2, t0_2)
#单元格排序
# 创建一个表格对象
self.tableWidget = QTableWidget()
# 设置行列数
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(3)
layout1 = QVBoxLayout()
layout1.addWidget(self.tableWidget)
# 设置表头的行标签
self.tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '年龄'])
# 创建单元格对象
Item1 = QTableWidgetItem('老王')
self.tableWidget.setItem(0, 0, Item1)
Item2 = QTableWidgetItem("男")
self.tableWidget.setItem(0, 1, Item2)
Item3 = QTableWidgetItem('30')
self.tableWidget.setItem(0, 2, Item3)
Item1 = QTableWidgetItem('隔壁老王')
self.tableWidget.setItem(1, 0, Item1)
Item2 = QTableWidgetItem("男")
self.tableWidget.setItem(1, 1, Item2)
Item3 = QTableWidgetItem('32')
self.tableWidget.setItem(1, 2, Item3)
Item1 = QTableWidgetItem('隔壁小王')
self.tableWidget.setItem(2, 0, Item1)
Item2 = QTableWidgetItem("女")
self.tableWidget.setItem(2, 1, Item2)
Item3 = QTableWidgetItem('18')
self.tableWidget.setItem(2, 2, Item3)
self.button = QPushButton("排序")
self.button.clicked.connect(self.order)
self.buttonq = QPushButton("表右键")
self.buttonq.clicked.connect(self.orderq)
# 设置默认为降序排列
self.orderType = Qt.DescendingOrder
layout1.addWidget(self.button)
layout1.addWidget(self.buttonq)
#合并单元格
layout2 = QHBoxLayout()
tableWidget = QTableWidget()
tableWidget.setRowCount(5)
tableWidget.setColumnCount(3)
layout2.addWidget(tableWidget)
tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '年龄'])
Item1 = QTableWidgetItem('老王')
# 设置单元格对齐方式:常量在Qt中
Item1.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)
#设置行高
tableWidget.setRowHeight(2,80)
tableWidget.setColumnHidden(2, 80)
Item2 = QTableWidgetItem('隔壁')
Item2.setFont(QFont('Times', 30, QFont.Black))
Item2.setForeground(QBrush(QColor(255, 0, 0)))
#图片加文字
Item3 = QTableWidgetItem(QIcon('img.png'),'隔壁')
tableWidget.setItem(3, 0, Item3)
#图片样式
tableWidget.setColumnWidth(0,100)
tableWidget.setRowHeight(4,100)
Item4 = QTableWidgetItem()
Item4.setIcon(QIcon('img.png'))
tableWidget.setItem(4, 0, Item4)
Item5 = QTableWidgetItem()
Item5.setIcon(QIcon('img_2.png'))
tableWidget.setItem(4, 1, Item5)
#显示右键菜单
tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
tableWidget.customContextMenuRequested.connect(self.on_yjj)
tableWidget.setItem(2, 0, Item2)
tableWidget.setItem(0, 0, Item1)
tableWidget.setSpan(0, 0, 2, 2)
# 单元格摆放控件
layout = QHBoxLayout()
tableWidget = QTableWidget()
# 指定行列数
tableWidget.setRowCount(41)
tableWidget.setColumnCount(4)
layout.addWidget(tableWidget)
tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '年龄'])
# 创建单元格文本
textItem = QTableWidgetItem("老王")
tableWidget.setItem(0, 0, textItem)
# 创建下拉控件
combox = QComboBox()
combox.addItem("男")
combox.addItem("女")
# QSS Qt StyleSheet
combox.setStyleSheet('QComboBox{margin:3px}')
# 向QTableWidget添加控件
tableWidget.setCellWidget(0, 1, combox)
button = QPushButton("修改")
# 设置默认为按下的状态
button.setDown(True)
button.setStyleSheet('QPushButton{margin:3px}')
tableWidget.setCellWidget(0, 2, button)
# 快速定位行
self.bbt = QPushButton('定位')
self.exs = QLineEdit()
self.exs.setPlaceholderText("输入搜索行数[1-40]")
xla = QHBoxLayout()
xla.addWidget(self.exs)
xla.addWidget(self.bbt)
for i in range(40):
for j in range(4):
itemContent = '(%d, %d)' % (i, j)
tableWidget.setItem(i, j, QTableWidgetItem(itemContent))
# 搜索满足条件的Cell
text = '(34,'
# 第一个参数为要搜索的单元格的内容,第二个参数为设置精确搜索
# items = tableWidget.findItems(text, QtCore.Qt.MatchExactly)
# 设置以该text开头的进行匹配搜索
items = tableWidget.findItems(text, QtCore.Qt.MatchStartsWith)
if len(items) > 0:
item = items[0]
item.setBackground(QBrush(QColor(0, 255, 0)))
item.setBackground(QBrush(QColor(255, 0, 0)))
row = item.row()
# 定位到指定的行
tableWidget.verticalScrollBar().setSliderPosition(row)
#列表模型
listm=QListView()#模型
lmd=QStringListModel()
self.list=["列表1","列表2","列表3"]
#列表内添加
# self.lists=QListWidget()
# self.lists.addItem("列表f")
lmd.setStringList(self.list)#列表模型赋值列表
listm.setModel(lmd)#模型赋值模型列表
listm.clicked.connect(self.on_lbts)
#excel列表布局
lay = QVBoxLayout()
lay.addLayout(xla)
lay.addWidget(self.tab)
lay.addWidget(listm)
xxla=QHBoxLayout()
xxla.addLayout(layout2)
xxla.addLayout(lay)
#总布局
zbj=QVBoxLayout()
zbj.addLayout(layout)
zbj.setStretch(0, 3)
zbj.addLayout(xxla)
zbj.setStretch(1, 3)
zbj.addLayout(layout1)
zbj.setStretch(2, 1)
dia3.setLayout(zbj)
dia3.exec_()
#右键菜单
def orderq(self):
dia4=QDialog()
conLayout = QHBoxLayout()
self.tableWidget = QTableWidget()
self.tableWidget.setRowCount(5)
self.tableWidget.setColumnCount(3)
conLayout.addWidget(self.tableWidget)
self.tableWidget.setHorizontalHeaderLabels(["姓名", "性别", "体重"])
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
newItem = QTableWidgetItem("张三")
self.tableWidget.setItem(0, 0, newItem)
newItem = QTableWidgetItem("男")
self.tableWidget.setItem(0, 1, newItem)
newItem = QTableWidgetItem("160")
self.tableWidget.setItem(0, 2, newItem)
newItem = QTableWidgetItem("李四")
self.tableWidget.setItem(1, 0, newItem)
newItem = QTableWidgetItem("女")
self.tableWidget.setItem(1, 1, newItem)
newItem = QTableWidgetItem("170")
self.tableWidget.setItem(1, 2, newItem)
# 允许右键产生菜单
self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
# 将右键菜单绑定到槽函数
self.tableWidget.customContextMenuRequested.connect(self.generateMenu)
dia4.setLayout(conLayout)
dia4.exec_()
def generateMenu(self, pos):
row_num = -1
for i in self.tableWidget.selectionModel().selection().indexes():
row_num = i.row()
if row_num < 2:
menu = QMenu()
item1 = menu.addAction(u"选项一")
item2 = menu.addAction(u"选项二")
item3 = menu.addAction(u"选项三")
action = menu.exec_(self.tableWidget.mapToGlobal(pos))
if action == item1:
print("你选了选项一,当前行文字内容是:", self.tableWidget.item(row_num, 0).text(),
self.tableWidget.item(row_num, 1).text(), self.tableWidget.item(row_num, 2).text())
elif action == item2:
print("你选了选项二,当前行文字内容是:", self.tableWidget.item(row_num, 0).text(),
self.tableWidget.item(row_num, 1).text(), self.tableWidget.item(row_num, 2).text())
elif action == item3:
print("你选了选项三,当前行文字内容是:", self.tableWidget.item(row_num, 0).text(),
self.tableWidget.item(row_num, 1).text(), self.tableWidget.item(row_num, 2).text())
else:
return
def on_yjj(self,poo):
print(poo)
for i in self.tableWidget.selectionModel().selection().indexes():
row=i.row()
if row < 2:
meny=QMenu()
itm=meny.addAction('菜单1')
itm1=meny.addAction('菜单2')
itm2 = meny.addAction('菜单3')
ass=meny.exec(poo)
if ass == itm:
print('选择1',self.tableWidget.item(row,0).text(),
self.tableWidget.item(row,1).text(),
self.tableWidget.item(row,2).text())
elif ass==itm1:
print('选择2', self.tableWidget.item(row, 0).text(),
self.tableWidget.item(row, 1).text(),
self.tableWidget.item(row, 2).text())
elif ass==itm2:
print('选择2', self.tableWidget.item(row, 0).text(),
self.tableWidget.item(row, 1).text(),
self.tableWidget.item(row, 2).text())
else:
return
def order(self):
if self.orderType == Qt.DescendingOrder:
self.orderType = Qt.AscendingOrder
else:
self.orderType = Qt.DescendingOrder
# 设置排序方式 sortItems(列, 排序方式)
self.tableWidget.sortItems(2, self.orderType)
def on_lbts(dia3,tiad):
QMessageBox.information(dia3,"QListView","你选择了:"+ dia3.list[tiad.row()])
def on_28(self,dia2):
dia2=QDialog()
dia2.resize(400,400)
self.printer=QPrinter()
self.exed = QTextEdit("我是测试打印区", dia2)
self.exed.setGeometry(20,20,280,300)
self.bt=QPushButton("打印",dia2)
self.bt.move(310,10)
self.bt.clicked.connect(self.on_bttt)
self.bt1=QPushButton("打开文件",dia2)
self.bt1.move(310,40)
self.bt1.clicked.connect(self.on_bttt1)
self.bt2 = QPushButton("打印设置", dia2)
self.bt2.move(310, 70)
self.bt2.clicked.connect(self.on_bttt2)
self.bt3 = QPushButton("打印文档", dia2)
self.bt3.move(310, 100)
self.bt3.clicked.connect(self.on_bttt3)
# dia2.show()
dia2.exec_()
def on_bttt1(self):
fnam=QFileDialog.getOpenFileName(self,"打开文档","./")
if fnam[0]:
with open(fnam[0],'r',encoding='utf-8',errors='ignore') as f:
self.exed.setText(f.read())
def on_bttt2(self):
prontlong=QPageSetupDialog(self.printer,self)
prontlong.exec_()
def on_bttt3(self):
prinlong=QPrintDialog(self.printer,self)
if QDialog.Accepted == prinlong.exec_():
self.exed.print(self.printer)
def on_bttt(self):
printer=QtPrintSupport.QPrinter()#链接打印机
paint=QtGui.QPainter()
paint.begin(printer)
screen=self.exed.grab()#获取exed内容
paint.drawPixmap(10,10,screen)#画内容
paint.end()
def on_ss(self,a):
print("你按下了的是 ", a.text())
def ppo(self):
print(self.sender().text())
def oop(self,p):
if p.text() == "show":
self.statusBar.showMessage(p.text() + "菜单被点击", 5000)
#窗口绘制按钮界面
def ckhz(self):
dialong=QDialog()
bu1=QPushButton('绘制直线',dialong)
bu1.move(20,20)
dialong.setWindowTitle("绘制界面")
dialong.move(300,300)
dialong.resize(300,500)
bu1.clicked.connect(self.hzzx1)
bu2 = QPushButton('绘制曲线', dialong)
bu2.move(20, 50)
bu2.clicked.connect(self.hzzx2)
bu3 = QPushButton('选项卡', dialong)
bu3.move(20, 80)
bu3.clicked.connect(self.xxk1)
bu4 = QPushButton('堆载项卡', dialong)
bu4.move(20, 110)
bu4.clicked.connect(self.xxk2)
bu5 = QPushButton('靠边项卡', dialong)
bu5.move(20, 140)
bu5.clicked.connect(self.xxk3)
bu5 = QPushButton('容纳项卡', dialong)
bu5.move(20, 170)
bu5.clicked.connect(self.xxk4)
bu6 = QPushButton('滚动条', dialong)
bu6.move(20, 200)
bu6.clicked.connect(self.xxk5)
dialong.exec_()
#滚动条
def xxk5(self):
self.dds=Demo()
self.dds.show()
#容纳文件
def xxk4(self):
self.assd=MultiWindows()
self.assd.show()
#靠边 选项卡
def xxk3(self):
self.atos=ToolButton()
self.atos.show()
#堆载选项卡
def xxk2(self):
dos=DemoStackedWidget()
dos.show()
#选项卡
def xxk1(self):
self.form = Tab()
self.form.show()
#
#日历
def rl(self):
dilo=QDialog()
dilo.setWindowTitle('日历')
dilo.resize(300, 300)
#创建日历
self.cal=QCalendarWidget(dilo)
self.cal.setMinimumDate(QDate(1988,1,1))
self.cal.setMaximumDate(QDate(2088,1,1))
self.cal.setGridVisible(True)#网格显示
self.cal.move(20,20)
#
self.label3 = QLabel(dilo)
self.label3.move(150,285)
self.button27=QPushButton('获取最大时间',dilo)
self.button27.clicked.connect(self.on_27)
self.button27.move(200,260)
self.cal.clicked.connect(self.showData)
dat = self.cal.selectedDate()
self.label3.setText(dat.toString("yyyy-MM-dd dddd"))#显示年月日-星期
#
ed1=QDateTimeEdit(dilo)
ed1.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
laa1=QLabel('能调一年',dilo)
laa1.move(0,240)
ed1.move(50,240)
#最大,最小调整
ed1.setMinimumDate(QDate.currentDate().addDays(-365))
ed1.setMaximumDate(QDate.currentDate().addDays(365))
ed2=QDateTimeEdit(QDateTime.currentDateTime(),dilo)
ed2.setDisplayFormat("yyyy/MM/dd HH-mm-ss")
ed2.move(50, 260)
ed2.setCalendarPopup(True)
ed3=QDateTimeEdit(QDate.currentDate(),dilo)
ed3.setDisplayFormat("yyyy.MM.dd")
ed3.move(50, 280)
ed4=QDateTimeEdit(QTime.currentTime(),dilo)
ed4.setDisplayFormat("HH:mm:ss")
ed4.move(50, 220)
dilo.show()
dilo.exec_()
def on_27(self,dat):
print(dat)
def showData(self,dat):
self.label3.setText((dat.toString("yyyy-MM-dd dddd")))
#绘制曲线
def hzzx2(self,dialong):
self.ddssq=sssa()
self.ddssq.show()
# dialong.close()
#绘制文字
def hzzx1(self):
dialong1 = QDialog()
text1=QLabel("我是python",dialong1)
text1.move(20,20)
self.text = "自律学习PyQt5"
painter = QPainter(self)
painter.begin(self)
painter.setPen(QColor(150, 43, 5))
painter.setFont(QFont('SimSun', 25))
painter.drawText(dialong1.rect(), Qt.AlignCenter, self.text)
painter.end()
dialong1.exec_()
# label布局----------------------------------------------------------------------
def cetan(self): # 局中
pmzb = QDesktopWidget().screenGeometry() # 获取屏幕宽度、高度
ckzb = self.geometry() # 界面宽度、高度
gg = (pmzb.width() - ckzb.width()) / 2
ww = (pmzb.height() - ckzb.height()) / 2
self.move(int(gg), int(ww))
def on_exit(self): # 退出
sed = self.sender() # 自定义的槽
print(sed.text() + '按钮被点击')
app = QApplication.instance() # 得到一个实例
app.quit() # 退出程序
# 获取窗体信息
def on_xx1(self):
zct = QWidget() # 创建Qt窗口
print('x= %d' % zct.x())
print('y= %d' % zct.y())
print('界面宽度= %d' % zct.width())
print('界面高度= %d' % zct.height())
def on_bh(self, text):
print("输入内容" + text)
def on_b3(self):
self.ded1.setPlainText("你好!\n"
"我是python")
def on_b4(self):
self.ded1.setHtml(' 你好,我是pyhton '+ '我是\n'
'页眉')
def on_b5(self):
print(self.ded1.toPlainText())
def on_b6(self):
print(self.ded1.toHtml())
def kg_an(self,btn):
print('按钮被点击<'+ btn.text() +'>')
def kg_an1(self):
if self.button7.isChecked():
print('按钮被选中')
else:
print('按钮未选中')
def rad_an(self):
radioButton=self.sender()
if radioButton.isChecked() == True:
print('<'+ radioButton.text() + '>被选中')
else:
print('<' + radioButton.text() + '>未选中')
def fxk_an(self):
# chtus1=self.fxk1.text() +'isChecked=' + str(self.fxk1.isChecked()) + "checkstate=" + str(self.fxk1.checkState()) + '\n'
# # chtus2 = self.fxk2.text() + ',isChecked=' + str(self.fxk2.isChecked()) + "checkstate=" + str(self.fxk2.checkState()) + '\n'
# # chtus3 = self.fxk3.text() + ',isChecked=' + str(self.fxk3.isChecked()) + "checkstate=" + str(self.fxk3.checkState()) + '\n'
# # print(chtus1 + chtus2 + chtus3)
# print(chtus1)
print('复选按钮被点击')
def cd_an(self,i):
self.la1.setText('你选择的是:' + self.cd.currentText())
self.la1.adjustSize()
for count in range(self.cd.count()):
print('itme'+str(count) + "=" + self.cd.itemText(count))
print('你选择的是',i,'相对应的是',self.cd.currentText())
def hdk_1(self):
print('当前值:%s' % self.hdk.value())
sizz=self.hdk.value()
self.label1.setFont(QFont('Arial', sizz)) # 设置字体大小
def sb_sub1(self):
self.la2.setText('当前值:' + str(self.sb.value()))
def gettp1(self):
fname,_=QFileDialog.getOpenFileName(self,'打开文件',".",'图形文件(*.jpg *.png)')
self.labea.setPixmap(QPixmap(fname))
def gettp2(self):
dialong=QFileDialog()
dialong.setFileMode(QFileDialog.AnyFile)
dialong.setFilter(QDir.Files)
if dialong.exec():
fils=dialong.selectedFiles()
f=open(fils[0],'r')
with f:
data=f.read()
self.edtxt.setText(data)
#窗体嵌套---子窗口1
def showQW(self):
dia=QDialog()
dia.resize(400,400)
dia.setWindowTitle('子窗口')
dia.setWindowModality(Qt.ApplicationModal)
self.button12=QPushButton('退出按钮',dia)
# self.button12.move(10,20)
self.button13 = QPushButton('新建窗口', dia)
# self.button13.move(10, 60)
self.button12.clicked.connect(dia.close)
self.button13.clicked.connect(self.shouzQW1)
#加载图片
self.button12a = QPushButton('加载图片', dia)
# self.button12a.move(10, 100)
self.labea=QLabel()
# self.labea.move(10, 160)
self.button12a.clicked.connect(self.gettp1)
# 加载文本
self.button12b = QPushButton('加载文本', dia)
# self.button12b.move(10, 140)
self.edtxt=QTextEdit()
self.button12b.clicked.connect(self.gettp2)
self.button23=QPushButton('树文件管理器',dia)
self.button24 = QPushButton('翻译', dia)
self.button23.clicked.connect(self.on_23)
self.button24.clicked.connect(self.on_24)
jahla=QVBoxLayout()
jahla.addWidget(self.button12a)
jahla.addWidget(self.labea)
jahla.addWidget(self.button12b)
jahla.addWidget(self.edtxt)
jahla.addWidget(self.button12)
jahla.addWidget(self.button13)
jahla.addWidget(self.button23)
jahla.addWidget(self.button24)
#子窗口1总布局
diax = QHBoxLayout()
diax.addLayout(jahla)
# diax.addLayout(layout)
dia.setLayout(diax)
dia.exec_()
def on_23(self):
dia2 = QDialog()
model = QDirModel()
tree = QTreeView(dia2)
tree.setModel(model)
tree.show()
diax3 = QHBoxLayout()
diax3.addWidget(tree)
dia2.setLayout(diax3)
# tree.exec_()
dia2.exec_()
def on_24(self):
dia2a = QDialog()
dia2a.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) # 置顶,且去掉边框
dia2a.setAttribute(Qt.WA_TranslucentBackground) # 窗体背景透明
# model = QDirModel()
# tree = QTreeView(dia2)
# tree.setModel(model)
# tree.show()
# diax3 = QHBoxLayout()
# diax3.addWidget(tree)
# dia2.setLayout(diax3)
# if __name__ == '__main__':
# app1a = QApplication(sys.argv)
MainWindow = windApp()
MainWindow.show()
dia2a.show()
dia2a.exec_()
# sys.exit( MainWindow.exec())
# tree.exec_()
# dia2a.exec_()
#子窗口2--------------------------------------------------------------------
def shouzQW1(self):
dia1 = QDialog()
dia1.move(300,300)
dia1.resize(400, 400)
dia1.setWindowTitle('子窗口')
dia1.setWindowModality(Qt.ApplicationModal)
self.button14 = QPushButton('退出按钮', dia1)
self.text='我是窗口文字'
# self.close()关闭前面窗口
self.button14.clicked.connect(dia1.close)
#绘制文本
# def paint(self, event):
# papt = QPainter(self)
# papt.begin()
# papt.setPen(QColor(150, 43, 5))
# papt.drawText(event.rect(), Qt.AlignCenter, self.text)
# papt.end()
# paint(self,event)
#拖拽功能
class Combo(QComboBox):#扩展控件
def __init__(self, title, parent):#A键入B启动事件
super(Combo, self).__init__(parent)#放下事件
self.setAcceptDrops(True)#能够拖拽
def dragEnterEvent(self, e):#A键入B启动事件
print(e)
if e.mimeData().hasText():
e.accept()
else:
e.ignore()
def dropEvent(self, e):#放下事件
self.addItem(e.mimeData().text())#得到数据
dia1.edit = QLineEdit()
dia1.edit.setDragEnabled(True)
com = Combo("Button", dia1)
lo = QFormLayout()
lo.addRow(QLabel("请把左边的文本拖拽到右边的下拉菜单中"),self.button14)
lo.addRow(dia1.edit, com)
##复制粘贴
textCopyButton = QPushButton("&复制文字")
textPasteButton = QPushButton("粘贴 &文字")
htmlCopyButton = QPushButton("C&复制 HTML")
htmlPasteButton = QPushButton("粘贴 &HTML")
imageCopyButton = QPushButton("Co&复制 图片")
imagePasteButton = QPushButton("粘贴 &图片")
self.textLabel = QLabel("等待 text")
self.imageLabel = QLabel()
self.imageLabel.setPixmap(QPixmap(os.path.join(os.path.dirname(__file__), "./images/Python2.ico")))
layout = QGridLayout()
layout.addWidget(textCopyButton, 0, 0)
layout.addWidget(imageCopyButton, 0, 1)
layout.addWidget(htmlCopyButton, 0, 2)
layout.addWidget(textPasteButton, 1, 0)
layout.addWidget(imagePasteButton, 1, 1)
layout.addWidget(htmlPasteButton, 1, 2)
layout.addWidget(self.textLabel, 2, 0, 1, 2)
layout.addWidget(self.imageLabel, 2, 2)
textCopyButton.clicked.connect(self.copyText)
textPasteButton.clicked.connect(self.pasteText)
htmlCopyButton.clicked.connect(self.copyHtml)
htmlPasteButton.clicked.connect(self.pasteHtml)
imageCopyButton.clicked.connect(self.copyImage)
imagePasteButton.clicked.connect(self.pasteImage)
diax=QVBoxLayout()
diax.addLayout(lo)
diax.addLayout(layout)
dia1.setLayout(diax)
dia1.exec_()
def copyText(self):
clipboard = QApplication.clipboard()
clipboard.setText("I've been clipped")
def pasteText(self):
clipboard = QApplication.clipboard()
self.textLabel.setText(clipboard.text())
def copyImage(self):
clipboard = QApplication.clipboard()
clipboard.setPixmap(QPixmap(os.path.join(os.path.dirname(__file__), "./images/python.jpg")))
def pasteImage(self):
clipboard = QApplication.clipboard()
self.imageLabel.setPixmap(clipboard.pixmap())
def copyHtml(self):
mimeData = QMimeData()
mimeData.setHtml("Bold andRed")
clipboard = QApplication.clipboard()
clipboard.setMimeData(mimeData)
def pasteHtml(self):
clipboard = QApplication.clipboard()
mimeData = clipboard.mimeData()
if mimeData.hasHtml():
self.textLabel.setText(mimeData.html())
# 显示右键菜单
def showMenu(self, pos):
# pos 鼠标位置
# 菜单显示前,将它移动到鼠标点击的位置
self.contextMenu.exec_(QCursor.pos()) # 在鼠标位置显示
# 获取选择行的内容
def selected_text(self):
try:
selected = self.selectedItems()
texts = ''
for item in selected:
if texts:
texts = texts + '\n' + item.text()
else:
texts = item.text()
except BaseException as e:
print(e)
return
return texts
def copy(self):
text = self.selected_text()
if text:
clipboard = QApplication.clipboard()
clipboard.setText(text)
def del_text(self):
try:
index = self.selectedIndexes()
row = []
for i in index:
r = i.row()
row.append(r)
for i in sorted(row, reverse=True):
self.takeItem(i)
except BaseException as e:
print(e)
return
self.signal.emit(row)
def showQW1(self):
tex=self.sender().text()
if tex=='关于对话框':
QMessageBox.about(self,'关于','这是一个关于对话框')
elif tex =='消息对话框':
reply=QMessageBox.information(self,'消息','这是一个消息对话框',QMessageBox.Yes |QMessageBox.No)
print(reply == QMessageBox.Yes)
if reply == QMessageBox.Yes:
print('点击确定YES')
elif tex =='警告对话框':
QMessageBox.warning(self,'警告','这是一个警告对话框',QMessageBox.Yes |QMessageBox.No)
elif tex == '错误对话框':
QMessageBox.critical(self, '错误', '这是一个错误对话框', QMessageBox.Yes | QMessageBox.No)
elif tex == '提问对话框':
QMessageBox.question(self, '错误', '这是一个错误对话框', QMessageBox.Yes | QMessageBox.No)
#获取列表
def getlb(self):
tims=('c','c++','python','java')
tim,ok=QInputDialog.getItem(self,'选择语音','列表',tims)
if ok and tim:
self.dit.setText(tim)
# # 获取文字
def getwz(self):
txt, ok = QInputDialog.getText(self, '输入文本框', '请输入文字')
if ok and txt:
self.dit1.setText(txt)
# # 获取整数
def getzs(self):
sum, ok = QInputDialog.getInt(self, '输入文本框', '请输入文字')
if ok and sum:
self.dit2.setText(str(sum))
def get_zt(self):
font,ok=QFontDialog.getFont()
if ok:
self.label1.setFont(font)
#字体颜色
def get_zt1(self):
clor=QColorDialog.getColor()
pp=QPalette()
pp.setColor(QPalette.WindowText, clor)
self.label1.setPalette(pp)
#背景颜色
def get_zt2(self):
clor = QColorDialog.getColor()
pp = QPalette()
pp.setColor(QPalette.Window, clor)
self.label1.setAutoFillBackground(True)
self.label1.setPalette(pp)
#class类别------------------------------------------------------------------------------
class Tab(QTabWidget):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle('QTabWidget的使用')
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tab3 = QWidget()
#添加选项卡
self.addTab(self.tab1, 'Tab 1')
self.addTab(self.tab2, 'Tab 2')
self.addTab(self.tab3, 'Tab 3')
#设置选项卡
self.tab1UI()
self.tab2UI()
self.tab3UI()
def tab1UI(self):
layout = QFormLayout()
layout.addRow('姓名',QLineEdit())
layout.addRow('地址', QLineEdit())
self.setTabText(0,'联系方式')
self.tab1.setLayout(layout)
def tab2UI(self):
layout = QFormLayout()
sex = QHBoxLayout()
sex.addWidget(QRadioButton('男'))
sex.addWidget(QRadioButton('女'))
layout.addRow(QLabel('性别'),sex)
layout.addRow('生日',QLineEdit())
self.setTabText(1,'个人详细信息')
self.tab2.setLayout(layout)
def tab3UI(self):
layout = QHBoxLayout()
layout.addWidget(QLabel('科目'))
layout.addWidget(QCheckBox('物理'))
layout.addWidget(QCheckBox('高数'))
self.setTabText(2,'教育程度')
self.tab3.setLayout(layout)
#-------------绘图
class sssa(QWidget):
def __init__(self):
super(sssa, self).__init__()
self.resize(600,600)
self.setWindowTitle('直线')
def paintEvent(self,event):#自动脚本子程序
self.text='我是python'
pat=QPainter(self)
pat.begin(self)#初始化
pen=QPen(Qt.red,3,Qt.SolidLine)#直线
pat.setPen(pen)
pat.drawLine(20,40,250,40)
pen.setStyle(Qt.DashLine)#虚线
pat.setPen(pen)
pat.drawLine(20, 80, 250, 80)
pen.setStyle(Qt.DashDotDotLine)#虚点线
pat.setPen(pen)
pat.drawLine(20, 120, 250, 120)
pen.setStyle(Qt.DotLine) # 虚点线
pat.setPen(pen)
pat.drawLine(20, 160, 250, 160)
pen.setStyle(Qt.DashDotDotLine) # 虚点线
pat.setPen(pen)
pat.drawLine(20, 180, 250, 180)
pen.setStyle(Qt.CustomDashLine) # 虚点线
pen.setDashPattern([1,4,5,4])
pat.setPen(pen)
pat.drawLine(20, 200, 250, 200)
#文字中心
pat.setPen(QColor(150,43,5))
pat.setFont(QFont('SimSun',25))
pat.drawText(event.rect(),Qt.AlignCenter,self.text)
#曲线
size = self.size()
for i in range(1000):
x = 100 * (-1 + 2.0 * i / 1000) + size.width() / 2.0
# T = 50
y = -50 * math.sin((x - size.width() / 2.0) * math.pi / 50) + size.height() / 2.0
pat.drawPoint(int(x), int(y))
size = self.size()
#2/1半圆
pat.setPen(Qt.blue)
rect=QRect(200,10,100,100)
pat.drawArc(rect,0,50 * 16)
#红色圆
pat.setPen(Qt.red)
pat.drawArc(350,10,100,100,0,360 * 16)
#红色圆带旋
pat.drawChord(450,10,100,100,12,130*16)
#扇形
pat.drawPie(450,100,100,100,12,130*16)
#椭圆
pat.drawEllipse(250,120,150,100)
#正五边形
pt1=QPoint(450,150)
pt2 = QPoint(500, 200)
pt3 = QPoint(450, 250)
pt4 = QPoint(350, 250)
pt5 = QPoint(350, 150)
polygon=QPolygon([pt1,pt2,pt3,pt4,pt5])
pat.drawPolygon(polygon)
#图片
imge=QImage('img.png')
rect=QRect(10,300,int(imge.width()/1.5),int(imge.height()/1.5))
pat.drawImage(rect,imge)
#填充区域纯黑
br=QBrush(Qt.SolidPattern)
pat.setBrush(br)
pat.drawRect(10,450,90,60)
# 填充区域点黑
br = QBrush(Qt.Dense1Pattern)
pat.setBrush(br)
pat.drawRect(150,450, 90, 60)
# 填充区域点黑
br = QBrush(Qt.Dense2Pattern)
pat.setBrush(br)
pat.drawRect(300, 450, 90, 60)
# 填充区域点黑
br = QBrush(Qt.Dense3Pattern)
pat.setBrush(br)
pat.drawRect(450, 450, 90, 60)
pat.end()#结束
#
class DemoStackedWidget(QMainWindow):
def __init__(self, parent=None):
super(DemoStackedWidget, self).__init__(parent)
# 设置窗口标题
self.setWindowTitle('实战PyQt5: QStackedWidget Demo!')
# 设置窗口大小
self.resize(480, 360)
self.initUi()
def initUi(self):
toolBar = QToolBar(self)
self.addToolBar(Qt.LeftToolBarArea, toolBar)
btnColor = self.createButton('颜色对话框')
btnColor.clicked.connect(lambda: self.onButtonClicked(0))
toolBar.addWidget(btnColor)
btnFont = self.createButton('字体对话框')
btnFont.clicked.connect(lambda: self.onButtonClicked(1))
toolBar.addWidget(btnFont)
btnUser = self.createButton('分组部件')
btnUser.clicked.connect(lambda: self.onButtonClicked(2))
toolBar.addWidget(btnUser)
self.mainWidget = QStackedWidget(self)
# 添加三个widget,演示三个页面之间的切换
# 颜色对话框
self.mainWidget.addWidget(QColorDialog(self))
# 字体对话框
self.mainWidget.addWidget(QFontDialog(self))
# 自定义控件
self.mainWidget.addWidget(self.createExclusiveGroup())
# 设置中心窗口
self.setCentralWidget(self.mainWidget)
def createButton(self, text):
icon = QApplication.style().standardIcon(QStyle.SP_DesktopIcon)
btn = QToolButton(self)
btn.setText(text)
btn.setIcon(icon)
btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
return btn
def onButtonClicked(self, index):
if index < self.mainWidget.count():
self.mainWidget.setCurrentIndex(index)
def createExclusiveGroup(self):
groupBox = QGroupBox('Exclusive Radio Buttons', self)
radio1 = QRadioButton('&Radio Button 1', self)
radio1.setChecked(True)
radio2 = QRadioButton('R&adio button 2', self)
radio3 = QRadioButton('Ra&dio button 3', self)
vLayout = QVBoxLayout(groupBox)
vLayout.addWidget(radio1)
vLayout.addWidget(radio2)
vLayout.addWidget(radio3)
vLayout.addStretch(1)
groupBox.setLayout(vLayout)
return groupBox
class ToolButton(QMainWindow):
def __init__(self):
super(ToolButton, self).__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("ToolButton")
self.setGeometry(400, 400, 300, 260)
self.toolbar = self.addToolBar("toolBar")
self.statusBar()
self._detailsbutton = QToolButton()
self._detailsbutton.setCheckable(True)
self._detailsbutton.setChecked(False)
self._detailsbutton.setArrowType(Qt.RightArrow)
self._detailsbutton.setAutoRaise(True)
# self._detailsbutton.setIcon(QIcon("test.jpg"))
self._detailsbutton.setToolButtonStyle(Qt.ToolButtonIconOnly)
self._detailsbutton.clicked.connect(self.showDetail)
self.toolbar.addWidget(self._detailsbutton)
def showDetail(self):
if self._detailsbutton.isChecked():
self.statusBar().showMessage("我被点击")
else:
self.statusBar().showMessage("关闭")
class MultiWindows(QMainWindow): # 直接一整个屏幕就是一个选项卡窗口
count = 0 # 记录当前有多少个菜单项
def __init__(self, parent=None):
super(MultiWindows, self).__init__(parent)
self.setWindowTitle('容纳多文档的窗口')
self.setGeometry(800, 450, 500, 400) # x,y,w,h
# 容纳多文档容器对象
self.mdi = QMdiArea()
bar = self.menuBar()
file = bar.addMenu('File')
file.addAction('New')
file.addAction('cascade') # 重叠
file.addAction('Tiled') # 平铺
file.triggered.connect(self.windowAction)
self.setCentralWidget(self.mdi)
def windowAction(self, q): # q是当前的单击菜单项,通过按钮名来进行不同的操作
if q.text() == 'New':
self.count = self.count + 1
# 子窗口对象
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle('子窗口' + str(self.count))
self.mdi.addSubWindow(sub)
sub.show()
# 下面两个是对mdi中已有的窗口排布进行操作,而不是生成窗口
elif q.text() == 'cascade':
self.mdi.cascadeSubWindows()
elif q.text() == 'Tiled':
self.mdi.tileSubWindows()
class Demo(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(100, 50, 500, 400)
self.setWindowTitle('QScrollBar的使用')
layout = QHBoxLayout()
self.l1 = QLabel('拖动滑块改变颜色')
self.l1.setFont(QFont('Arial', 16))
layout.addWidget(self.l1)
self.s1 = QScrollBar()
self.s1.setMaximum(255)
self.s1.sliderMoved.connect(self.sliderval)
self.s2 = QScrollBar()
self.s2.setMaximum(255)
self.s2.sliderMoved.connect(self.sliderval)
self.s3 = QScrollBar()
self.s3.setMaximum(255)
self.s3.sliderMoved.connect(self.sliderval)
layout.addWidget(self.s1)
layout.addWidget(self.s2)
layout.addWidget(self.s3)
self.setLayout(layout)
def sliderval(self):
print(self.s1.value(), self.s2.value(), self.s3.value())
palette = QPalette()
c = QColor(self.s1.value(), self.s2.value(), self.s3.value(), 255)
palette.setColor(QPalette.Foreground, c)
self.l1.setPalette(palette)
class BackendThread(QThread):
update_date = pyqtSignal(str)
def run(self):
while True:
data = QDateTime.currentDateTime()
currentTime = data.toString("yyyy-MM-dd hh:mm:ss")
self.update_date.emit(str(currentTime))
time.sleep(1)
class ThreadUpdateUI(QDialog):
def __init__(self):
QDialog.__init__(self)
self.setWindowTitle('多线程更新UI数据')
self.resize(400,100)
self.input = QLineEdit(self)
self.input.resize(400,100)
self.initUI()
def initUI(self):
self.backend = BackendThread()
self.backend.update_date.connect(self.handleDisplay)
self.backend.start()
def handleDisplay(self,data):
self.input.setText(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Zzck() # 这里设置图标可以生成应用程序图标
main.show()
#5秒自动消失-----------
#
# label = QLabel('Hello World,窗口在5秒后自动关闭!')
# # setWindowFlag设置窗口属性:启动画面,无框架
# label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
# label.show()
# # 5秒之后退出整个程序
# QTimer.singleShot(5000, apd.quit)
# 5秒自动消失------------
sys.exit(app.exec_())