最近需要用 PyQt 渲染 LaTeX 公式,怎么办呢?思来想去得到了一个精妙的解决方案,分为两步:
- 用 Matplotlib 渲染 LaTeX 并保存成图片
- PyQt 显示图片
Matplotlib 渲染 LaTeX 并保存成图片
直接上函数的代码以供复制。函数将字符串 a 用 LaTeX 渲染并保存到 path 里。
import matplotlib.pyplot as plt
def renderLaTeX(a, path, usetex=True, dpi=500, fontsize=20):
acopy = a
plt.figure(figsize=(0.3,0.3))
if usetex: #使用真正的 LaTeX 渲染
try:
a = '$\\displaystyle ' + a.strip('$') + ' $'
plt.text(-0.3,0.9, a, fontsize=fontsize, usetex=usetex)#
except:
usetex = False
if not usetex:
a = acopy
a = a.strip('$')
a = '\n'.join([' $ '+_+' $ ' for _ in a.split('\\\\')])
plt.text(-0.3,0.9, a, fontsize=fontsize, usetex=usetex)
plt.ylim(0,1)
plt.xlim(0,6)
plt.axis('off') #隐藏坐标系
plt.savefig(path, dpi=dpi, bbox_inches ='tight')
plt.close() #释放内存
代码解释:
-
用 plt.text 输出图片。如果参数 usetex=True 会调用真正的 LaTeX 渲染,如果 usetex=False 则使用 matplotlib 内置的方法渲染。前者的公式更加美观,但是要慢一点。
-
这里将 plt.figure 的 figsize 设置非常小,使得在窗口里无法展示完整的公式。但是因为有 savefig 里的参数 bbox_inches = ‘tight’ ,公式被完整地保存成图片,且没有留出过大的空白!
-
代码中对字符串 a 的处理考虑到了其换行符 (\\)。
PyQt 展示图片
以下以 PySide 6 为例。假设刚刚保存图片的路径为 ‘Formula.png’.
from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.display = QtWidgets.QLabel(self)
self.display.setStyleSheet('border:2px groove gray')
self.display.setAlignment(QtCore.Qt.AlignCenter)
pix = QtGui.QPixmap('Formula.png').scaled(400,300,
QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
self.display.setGeometry(0,0,400,300)
self.display.setPixmap(pix)
示例
执行 ( usetex 默认为 True , 即调用真正的 LaTeX)
renderLaTeX(r'c:\ |z|=1 \\ \frac{1}{2\pi i}\int_c \frac{f(z)}{z-z_0}dz = Res_{z=z_0}f(z)','Formula.png')
则 Formula.png 为: