重写pyqt4/pyside中的QTextEdit类实现ctrl+鼠标左键对内容进行缩放

在实际的Ui界面开发过程中为了实现一些比较方便的功能就需要对pyqt/pyside中的一些class进行重写。下面我就重写了QTextEdit类实现ctrl+鼠标左键对内容进行缩放。下面是重写的代码,博主使用的是PySide,你也可以使用PyQt:

#!usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@author:MCC
@file: __init__
@time: 2018/08/15 19:00
"""

import sys

try:
    from PySide import QtCore
    from PySide import QtGui as QtWidgets
except ImportError:
    from PySide2 import QtCore
    from PySide2 import QtWidgets


class MyTextEdit(QtWidgets.QWidget):
    """This class rewrites textEdit's ctrl-mouse left-click to scale the font"""
    def __init__(self, parent=None):
        super(MyTextEdit, self).__init__(parent)
        self.zoom_size = 2
        self.ctrl_pressed = False

    def wheelEvent(self, event):
        if self.ctrl_pressed:
            delta = event.delta()
            oriention = delta / 8
            self.zoom_size = 0
            if oriention > 0:
                self.zoom_size +=1
            else:
                self.zoom_size -=1
            self.zoomIn(self.zoom_size)

        else:
            return super(MyTextEdit, self).wheelEvent(event)

    def keyReleaseEvent(self, QkeyEvent):
        if QkeyEvent.key() == QtCore.Qt.Key_Control:
            self.ctrl_pressed = False
        return super(MyTextEdit, self).keyReleaseEvent(QkeyEvent)

    def keyPressEvent(self, QkeyEvent):
        if QkeyEvent.key() == QtCore.Qt.Key_Control:
            self.ctrl_pressed = True
        return super(MyTextEdit, self).keyPressEvent(QkeyEvent)


使用时只需要继承或调用这个class就可以实现对TextEdit里的内容进行缩放了。希望对大家有所帮助。

你可能感兴趣的:(PySide/PyQt)