python PyQt5
# _*_ coding:utf-8 _*_
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout,
QPushButton, QMainWindow)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.init_ui()
def init_ui(self):
self.setWindowTitle('关闭主窗口')
# 设置窗口标题
self.resize(600, 600)
layout = QVBoxLayout()
self.close_btn = QPushButton('关闭', self)
layout.addWidget(self.close_btn)
main_frame = QWidget()
self.setCentralWidget(main_frame)
main_frame.setLayout(layout)
self.close_btn.clicked.connect(self.on_button_click)
self.status = self.statusBar()
self.status.showMessage('我是状态栏', 5000)
def on_button_click(self):
# 将信息显示在状态栏中
sender = self.sender()
msg = sender.text() + " 被按下了"
status = self.statusBar()
status.showMessage(msg, 5000)
#self.showMaximized()
# 程序退出
app = QApplication.instance()
app.quit()
if __name__ == "__main__":
app = QApplication(sys.argv[1:])
window = MainWindow()
window.show()
sys.exit(app.exec_())
===============================
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QColor, QFont, QIcon, QKeySequence from PyQt5.QtCore import Qt, QDate, QTime, QDateTime, QTimer from PyQt5.QtPrintSupport import QPrinter, QPrintDialog, QPrintPreviewDialog import os class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.initUI() def initUI(self): self.setWindowTitle("主窗口示例") # self.resize(400,250) self.setup_centralWidget() self.setup_dockWidget() self.setup_statusBar() self.createActions() self.setup_menuBar() self.setup_toolBar() def setup_centralWidget(self): # 设置主窗口中心部件 self.textEdit = QTextEdit() # 初始化时换行符无效 self.textEdit.setText("第一行\n第二行\n第三行\n") # self.textEdit.selectAll() self.setCentralWidget(self.textEdit) # 指定主窗口中心部件 def createActions(self): # 创建动作 # 打开文件动作 self.fileOpenAction = QAction(QIcon("open.png"), "&Open", self) # 动作在self中可用 self.fileOpenAction.setShortcut(QKeySequence.Open) # 设置标准化快捷键 # self.fileOpenAction.setShortcut("Ctrl+O")# windows 系统下等效于 self.fileOpenAction.setToolTip("打开文件") # 工具栏提示文本 self.fileOpenAction.setStatusTip("打开现有的文件") # 状态栏提示文本 self.fileOpenAction.triggered.connect(self.fileOpen) # 文件另存为动作 self.fileSaveAsAction = QAction(QIcon("save.png"), "SaveAs", self) # 动作在self中可用 self.fileSaveAsAction.setShortcut(QKeySequence.SaveAs) # 设置标准化快捷键 # windows 系统下无快捷键 self.fileSaveAsAction.setToolTip("另存为") # 工具栏提示文本 self.fileSaveAsAction.setStatusTip("文件另存为") # 状态栏提示文本 self.fileSaveAsAction.triggered.connect(self.fileSaveAs) # 动作分隔符 self.separator = QAction(self) self.separator.setSeparator(True) def setup_menuBar(self): # 文件菜单 self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.fileOpenAction) self.fileMenu.addAction(self.fileSaveAsAction) # self.fileMenu.addAction(self.separator) def fileOpen(self): fileName, filetype = QFileDialog.getOpenFileName(self, "打开文件", os.getcwd(), # 设定起始路径为当前目录 "Text Files (*.txt)") # 设置文件扩展名过滤,用双分号间隔 if fileName != "": with open(fileName) as f: self.textEdit.setText(f.read()) def fileSaveAs(self): fileName, filetype = QFileDialog.getSaveFileName(self, "文件另存为", os.getcwd(), # 起始路径 "Text Files (*.txt);;Html Files (*.html)") # 设置文件扩展名过滤,用双分号间隔 if fileName == "": return if filetype == "Text Files (*.txt)": with open(fileName, "w") as f: f.write(self.textEdit.toPlainText()) elif filetype == "Html Files (*.html)": with open(fileName, "w") as f: f.write(self.textEdit.toHtml()) def setup_toolBar(self): fileToolbar = self.addToolBar("File") # 添加工具条;可依次添加多个工具条 fileToolbar.addActions((self.fileOpenAction, self.fileSaveAsAction, self.separator)) # 添加动作 tb_label1 = QLabel("选择什么东东") self.cb = QComboBox() self.cb.addItems(("红", "绿", "蓝")) fileToolbar.addWidget(tb_label1) # 工具条添加部件 fileToolbar.addWidget(self.cb) # 工具条添加部件 # ...... def setup_dockWidget(self): # 设置停靠窗口 self.logDockWidget = QDockWidget("log", self) self.logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.listWidget = QListWidget() self.logDockWidget.setWidget(self.listWidget) self.addDockWidget(Qt.RightDockWidgetArea, self.logDockWidget) # 添加停靠窗口 def setup_statusBar(self): # 配置状态栏 self.dateLabel = QLabel() self.dateLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.dateLabel.setText(QDate.currentDate().toString()) self.timeLabel = QLabel() self.timeLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.timeLabel.setText(QTime.currentTime().toString()) self.statusBar().addPermanentWidget(self.dateLabel) self.statusBar().addPermanentWidget(self.timeLabel) datetime = QDateTime.currentDateTime().toString() self.statusBar().showMessage(datetime, 3000) # 状态栏在3000ms内显示信息 self.statusBar().showMessage("ready") # 状态栏显示信息 timer = QTimer(self) # 创建计时器#self timer.timeout.connect(self.updateBySecond) # 计时器超时信号接到用于更新界面的槽 timer.start(1000) # 每1000ms发射超时信号 def updateBySecond(self): self.timeLabel.setText(QTime.currentTime().toString()) self.dateLabel.setText(QDate.currentDate().toString()) if __name__ == '__main__': app = QApplication(sys.argv) mw = MainWindow() mw.show() sys.exit(app.exec_()) #本文分享自微信公众号 - Python
======================
import sys from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.Qt import QRegExp, QRegExpValidator from PyQt5.QtWidgets import * # 非模态对话框("Apply"型更新),自定义信号,数据验证,正则表达式,掩码 class NumberFormatDlg(QDialog): changed = pyqtSignal() # 自定义信号 def __init__(self, format_, parent=None): super().__init__(parent) thousandsLabel = QLabel("&Thousands seprator") self.thousandsEdit = QLineEdit(format_["thousandsseparator"]) self.thousandsEdit.setMaxLength(1) # 正则表达式 punctuationRe = QRegExp(r"[ ,;:.]") # 只能为中括号内的某个字符,还可以为空 # 设定验证方式为正则表达式,不合规的字符输入不进去。预防式验证 self.thousandsEdit.setValidator(QRegExpValidator(punctuationRe, self)) thousandsLabel.setBuddy(self.thousandsEdit) decimalMarkerLabel = QLabel("Decimal &marker") self.decimalMarkerEdit = QLineEdit(format_["decimalmarker"]) self.decimalMarkerEdit.setMaxLength(1) self.decimalMarkerEdit.setValidator(QRegExpValidator(punctuationRe, self)) self.decimalMarkerEdit.setInputMask("X") # 设定掩码 decimalMarkerLabel.setBuddy(self.decimalMarkerEdit) decimalPlacesLabel = QLabel("&Decimal places") self.decimalPlacesSpinBox = QSpinBox() self.decimalPlacesSpinBox.setRange(0, 6) self.decimalPlacesSpinBox.setValue(format_["decimalplaces"]) decimalPlacesLabel.setBuddy(self.decimalPlacesSpinBox) self.redNegativesCheckBox = QCheckBox("&Red negative numbers") self.redNegativesCheckBox.setChecked(format_["rednegatives"]) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Close) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.apply) buttonBox.rejected.connect(self.reject) grid = QGridLayout() grid.addWidget(thousandsLabel, 0, 0) grid.addWidget(self.thousandsEdit, 0, 1) grid.addWidget(decimalMarkerLabel, 1, 0) grid.addWidget(self.decimalMarkerEdit, 1, 1) grid.addWidget(decimalPlacesLabel, 2, 0) grid.addWidget(self.decimalPlacesSpinBox, 2, 1) grid.addWidget(self.redNegativesCheckBox, 3, 0, 1, 2) grid.addWidget(buttonBox, 4, 0, 1, 2) self.setLayout(grid) self.setWindowTitle("数字格式设置(非模态)") self.format = format_ def apply(self): thousands = self.thousandsEdit.text() decimal = self.decimalMarkerEdit.text() # 提交后验证 #交叉验证 if thousands == decimal: QMessageBox.warning(self, "格式错误", "千位分隔符和小数点符不能相同") self.thousandsEdit.selectAll() self.thousandsEdit.setFocus() return if decimal == '': QMessageBox.warning(self, "格式错误", "小数点符不能为空") self.decimalMarkerEdit.selectAll() self.decimalMarkerEdit.setFocus() return self.format["thousandsseparator"] = thousands self.format["decimalmarker"] = decimal self.format["decimalplaces"] = self.decimalPlacesSpinBox.value() self.format["rednegatives"] = self.redNegativesCheckBox.isChecked() self.changed.emit() # 发射自定义信号 class MainDialog(QDialog): def __init__(self, parent=None): super(MainDialog, self).__init__(parent) format_ = dict(thousandsseparator=",", decimalmarker=".", decimalplaces=3, rednegatives=True) self.dialog = NumberFormatDlg(format_) button = QPushButton("click here", self) button.clicked.connect(self.dialog.show) app = QApplication(sys.argv) font = MainDialog() font.show() app.exec_()
==========================
鼠标操作
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.label = QLabel('Hello World', self)
self.label1 = QLabel('喂 世界', self)
self.label1.move(0, 30)
self.label2 = QLabel('鼠标位置', self)
self.resize(500, 300)
self.label.resize(200, 20)
self.label1.resize(200, 20)
self.label2.resize(400, 20)
self.label2.move(0, 60)
self.label3 = QLabel('鼠标位置', self)
self.label3.resize(400, 20)
self.label3.move(0, 90)
self.setMouseTracking(True) # 设置鼠标移动跟踪是否有效
'''
设置为True时,只要鼠标在窗口内移动时mouseMoveEvent事件就能捕获
设置为False时(默认),只有鼠标键按下并在窗口内移动时mouseMoveEvent事件才能捕获
注意只能是QWidget,如果是QMainwindow,则无效
self.hasMouseTracking()返回设置的状态
'''
def mousePressEvent(self, event): # 鼠标键按下时调用(任意一个键,按一下调一次),这些方法是许多控件自带的,这里来自于QWidget。
self.label.setText('鼠标键按下了')
n = event.button() # 用来判断是哪个鼠标健触发了事件【返回值:0 1 2 4】
'''
QtCore.Qt.NoButton - 0 - 没有按下鼠标键
QtCore.Qt.LeftButton -1 -按下鼠标左键
QtCore.Qt.RightButton -2 -按下鼠标右键
QtCore.Qt.Mion 或 QtCore.Qt.MiddleButton -4 -按下鼠标中键
'''
nn = event.buttons() # 返回前面所列枚举值的组合,用于判断同时按下了哪些键【不知怎么判断】 <PyQt5.QtCore.Qt.MouseButtons object at 0x0000003326982F98>
def mouseReleaseEvent(self, event): #鼠标键释放时调用
# #参数1:鼠标的作用对象;参数2:鼠标事件对象,用来保存鼠标数据
self.label.setText('鼠标键放开了')
def mouseMoveEvent(self, event): # 鼠标移动事件
ret = self.hasMouseTracking() #返回鼠标MouseTracking的状态
# self.label1.setText('鼠标移动了:%s' % ret)
x = event.x() # 返回鼠标相对于窗口的x轴坐标
y = event.y() # 返回鼠标相对于窗口的y轴坐标
# self.label2.setText('鼠标x坐标:%s ,鼠标y坐标:%s' % (x, y))
xy = event.pos() #返回鼠标坐标 ,QPoint(463, 0) 相对于控件 【用xy.x() xy.y()提取值】
s=event.localPos() #返回鼠标坐标 相对于控件 QPointF(2.0, 2.0)
s = self.mapToGlobal(xy) # 将窗口坐标转换成屏幕坐标.属于QWidget类的方法;参数类型QPoint
self.label3.setText('鼠标x坐标:%s ,鼠标y坐标:%s' % (xy.x(), xy.y()))
xy1 = event.globalPos() # 返回鼠标相对于屏幕的坐标。PyQt5.QtCore.QPoint(1096, 37)【用xy1.x() xy1.y()提取值】
s1 = self.mapFromGlobal(xy1) #将屏幕坐标转换成窗口坐标.属于QWidget类的方法;参数类型QPoint
# mapToParent(QPoint) - 将窗口坐标转换成父窗口坐标。如果没有父窗口,则相当于mapToGlobal (QPoint)
# mapFromParent(QPoint) - 将父窗口坐标转换成窗口坐标。如果没有父窗口,则相当于mapFromGlobal(QPoint)
# mapTo (QWidget, QPoint) - 将窗口坐标转换成 QWidget父窗口坐标
px = event.globalX() # 返回相对于屏幕的x坐标
py = event.globalY() # 返回相对于屏幕的y坐标
s = event.windowPos() # 相对于窗口的坐标(保留一位小数),PyQt5.QtCore.QPointF(481.0, 1.0)【用s.x() s.y()提取值】
p = event.screenPos() # 相对于屏幕的坐标(保留一位小数).PyQt5.QtCore.QPointF(476.0, 49.0)【用p.x() p.y()提取值】
t = event.timestamp() # 返回事件发生的时间。【以程序运行开始计时,以毫秒为单位】
def mouseDoubleClickEvent(self, event): # 鼠标双击时调用
self.label1.setText('双击了鼠标')
'''双击时的事件顺序如下:
MouseButtonPress
MouseButtonRelease
MouseButtonDblClick
MouseButtonPress
MouseButtonRelease
QApplicaption类的setDoubleClickInterval( )方法可设置双击的时间间隔;doubleClickInterval( )方法返回双击的时间间隔。'''
def enterEvent(self, event): # 鼠标移进时调用
print('鼠标移进窗口了')
self.setCursor(Qt.CrossCursor) # 设置鼠标形状。
# #需要from PyQt5.QtGui import QCursor,from PyQt5.QtCore import Qt
#鼠标形状对照图见下方
# self.unsetCursor() #鼠标恢复系统默认
def leaveEvent(self, event): # 鼠标移出时调用
print('鼠标移出窗口了')
def wheelEvent(self, event): # 滚轮滚动时调用。event是一个QWheelEvent对象
angle = event.angleDelta() # 返回滚轮转过的数值,单位为1/8度.PyQt5.QtCore.QPoint(0, 120)
angle = angle / 8 # 除以8之后单位为度。PyQt5.QtCore.QPoint(0, 15) 【向前滚是正数,向后滚是负数 用angle.y()取值】
ang = event.pixelDelta() # 返回滚轮转过的像素值 【不知为何 没有值】
# print(event.x(),event.y()) #返回鼠标相对于窗口的坐标
w = event.pos() # 返回相对于控件的当前鼠标位置.PyQt5.QtCore.QPoint(260, 173)
w1 = event.posF() # 返回相对于控件的当前鼠标位置.PyQt5.QtCore.QPointF(302.0, 108.0)
# 坐标函数与上面相同
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = Demo()
demo.show()
sys.exit(app.exec())
浙公网安备 33010602011771号