import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel
from ui import Ui_MainWindow # 由qtdesigner 生成的布局
class MyApp(QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
设置主窗口属性,居中显示
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication
class MyApp(QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.resize(512, 512) # 设置窗口的大小
self.status = self.statusBar() # 实例化创建状态栏
self.status.showMessage('状态栏提示', 4000) # # 将提示信息显示在状态栏中showMessage(‘提示信息’,显示时间(单位毫秒))
self.setWindowTitle('主窗口标题') # 设置窗口标题
self.setWindowIcon(QIcon('logo.png')) # 设置图标
self.move_center()
def move_center(self):
screen = QDesktopWidget().screenGeometry()
form = self.geometry()
x_move_step = (screen.width() - form.width()) / 2
y_move_step = (screen.height() - form.height()) / 2
self.move(x_move_step, y_move_step)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
label = QLabel(self)
label.setText("显示内容") # 写入
text = label.text() # 读取
label = QLabel(self)
pixmap = QPixmap("文件路径")
label.setPixmap(pixmap)
label.setScaledContents(True) # 设置图片随QLabel大小缩放
label.setAlignment(Qt.AlignCenter) # 设置图像居中显示
label = QLabel(self)
label.setPixmap(QPixmap("")) # 移除QLabel上的图片
img = cv2.imread("文件路径") # 读取图片,路径不能有中文
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # bgr -> rgb
h, w, c = img.shape # 获取图片形状
image = QImage(img, w, h, 3 * w, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
label.setPixmap(pixmap)
label.setScaledContents(True) # 设置图片随QLabel大小缩放
设置, 追加, 获取文本
text_browser = QTextBrowser(self)
text_browser.setText(a) # 设置文本
text_browser.append(a) # 追加文本
text = text_browser.toPlainText() # 获取文本
设置, 追加, 获取文本
text_edit = QTextEdit(self)
text_edit.setText(a) # 设置文本
text_edit.append(a) # 追加文本
text = text_edit.toPlainText() # 获取文本
按下触发事件
button = QPushButton(self)
button .setChecked() # 设置为可选中
button.clicked.connect(clicked_function) # 按下触发
def clicked_function():
pass
check_box = QCheckBox(self)
check_box.setChecked() # 默认设置为选中
check_box.setCheckable(True) # 设置为可被选中
check_box.stateChanged.connect(check_box_changed) # 状态改变触发check_box_changed函数
def use_external_camera(self, status):
if status == Qt.Checked: # 若状态为选中
pass
else:
pass
radio_button1 = QRadioButton()
radio_button2 = QRadioButton()
radio_button1.setChecked(True) # 设置选中,同时只能有一个选中
radio_button1.toggled.connect(radio_button_changed) # 按下触发radio_button_changed函数
radio_button2.setChecked(False) # 设置非选中
radio_button2.toggled.connect(radio_button_changed) # 按下触发radio_button_changed函数(共用同一个函数)
def radio_button_changed():
if radio_button1.isChecked(): #返回是否选中
pass
elif radio_button2.isChecked():
pass
QMessageBox对话框包含类型只是图标不同其他无太大差别:
reply = QMessageBox.information(self, "标题", "消息", QMessageBox.Yes | QMessageBox.No)
if reply==QMessageBox.Yes:
...
else:
...
滑动条设置上下限, 设置当前值, 滑动触发事件
slider = QSlider()
slider.setOrientation(Qtcore.Qt.Horizontal) # 设置为水平滑动条
# slider.setOrientation(Qtcore.Qt.Vertical) # 设置为竖直滑动条
slider.setMaximum(100) # 设置最大值
slider.setMinimum(0) # 设置最小值
slider.setValue(72) # 设置当前值
value = slider.value() #获取当前值
slider.valueChanged.connect(change_function) # 改变值时触发change_function函数
dialog = QDialog()
dialog.adjustSize() # 随内容自动改变大小
text = QLineEdit(message, dialog) # 添加空间显示提示文字
text.adjustSize()
# 设置窗口的属性为ApplicationModal模态,用户只有关闭弹窗后,才能关闭主界面
dialog.setWindowModality(Qt.ApplicationModal)
dialog.exec_() # 阻塞执行,只调用show执行后立马销毁
file_name, _ = QFileDialog.getOpenFileName(self, '标题', './', 'Image files(*.jpg *.gif *.png)') # 可设置默认路径与可选文件类型
folder_name = QFileDialog.getExistingDirectory(self, '标题', './') # 可设置默认路径
创建目录树结果并显示当前路径的树结构,双击文件触发函数
tree_model = QDirModel()
# 或者
# tree_model = QFileSystemModel()
# tree_model.setRootPath(os.getcwd()) # 设置根目录为当前目录
tree_view = QTreeView()
tree_view.setModel(tree_model )
tree_view.setRootIndex(self.dirModel.index(os.getcwd())) # 设置当前目录(没有这句话则为默认C盘路径)
tree_view.setWindowTitle(self.treeView.tr("当前目录")) # 显示title...好像没啥用
treeView.doubleClicked.connect(tree_cilcked_function) # 双击文件触发tree_cilcked_function函数
tree_view.show()
# 函数调用方式
def tree_cilcked_function(self, file_index):
file_name = tree_model.filePath(file_index)
...
设置计时时间,时间到触发时间,循环执行
timer = QTimer()
timer.timeout.connect(process_function)
timer.start(20) # 设置计时时间为20ms,并启动计时器
timer.stop() # 停止计时器
def process_function():
···
tray = QSystemTrayIcon(QIcon('./icon/cut.png'), self) # 创建系统托盘对象,传入主窗口
tray.activated.connect(func) # 设置托盘点击事件处理函数
tray_menu = QMenu(QApplication.desktop()) # 创建菜单
action1 = QAction(u'还原 ', self, triggered=func2) # 添加一级菜单动作选项(还原主窗口)
action2 = QAction(u'退出 ', self, triggered=fun3) # 添加一级菜单动作选项(退出程序)
tray_menu.addAction(action1) # 为菜单添加动作
tray_menu.addAction(action2)
tray.setContextMenu(tray_menu) # 设置系统托盘菜单
tray.show()
desktop = QApplication.desktop()
# 获取显示器分辨率大小
screenRect = desktop.screenGeometry()
height = self.screenRect.height()
width = self.screenRect.width()
screen = QApplication.primaryScreen()
pixmap = screen.grabWindow(0)
QWidget().adjustSize()
def mousePressEvent(self, QMouseEvent):
pass
def mouseReleaseEvent(self, QMouseEvent):
pass
def mouseMoveEvent(self, QMouseEvent):
pass
QMouseEvent的常用属性
QMouseEvent.x() # 鼠标坐标x
QMouseEvent.y() # 鼠标坐标y
QMouseEvent.button() # 按钮,枚举类型 Qt.LeftButton / Qt.RightButton
shot_bytes = QByteArray()
buffer = QBuffer(shot_bytes)
buffer.open(QIODevice.WriteOnly)
shot_img = self.get_shot_img()
shot_img.save(buffer, 'png') # 保存到buffer对象
data = shot_bytes.data() # 得到字节流