PyQt5 QLabel文字设置上标,下标应使用html结构语法,具体使用方法如下:
- 上标:<sup>上浮内容</sup>
- 下标:<sub>下浮内容</sub>
下面用个小例子演示,输入x值,计算x2和log10x,代码如下(第22、28行):
1 from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QLineEdit,QVBoxLayout, QHBoxLayout 2 from PyQt5.QtCore import QRegExp 3 from PyQt5.QtGui import QRegExpValidator,QIntValidator 4 import sys,math 5 6 class MyWin(QWidget): 7 8 def __init__(self): 9 super(MyWin, self).__init__() 10 self.setWindowTitle('上下标小例子') 11 self.setGeometry(500, 400, 300, 250) 12 13 self.ui_init() 14 15 def ui_init(self): 16 lbl_x=QLabel('请输入一个正整数:x =',self) 17 line_x=QLineEdit() 18 hbx1=QHBoxLayout() 19 hbx1.addWidget(lbl_x) 20 hbx1.addWidget(line_x) 21 22 lbl_xx = QLabel('x<sup>2</sup>=', self) 23 line_xx = QLineEdit() 24 hbx2 = QHBoxLayout() 25 hbx2.addWidget(lbl_xx) 26 hbx2.addWidget(line_xx) 27 28 lbl_log10x = QLabel('log<sub>10</sub>x=', self) 29 line_log10x = QLineEdit() 30 hbx3 = QHBoxLayout() 31 hbx3.addWidget(lbl_log10x) 32 hbx3.addWidget(line_log10x) 33 34 vbx=QVBoxLayout() 35 vbx.addLayout(hbx1) 36 vbx.addLayout(hbx2) 37 vbx.addLayout(hbx3) 38 self.setLayout(vbx) 39 40 pIntvalidator = QIntValidator(self) 41 pIntvalidator.setRange(1, 99) 42 line_x.setValidator(pIntvalidator) 43 44 line_x.textChanged.connect(lambda:self.show_result(line_x,line_xx,line_log10x)) 45 46 def show_result(self,line_x,line_xx,line_log10x): 47 x = int(line_x.text()) 48 xx=x**2 49 log10x=math.log(x,10) 50 line_xx.setText(str(xx)) #一定要转成字符串再赋值 51 line_log10x.setText(str(log10x)) 52 53 54 55 if __name__ == '__main__': 56 app = QApplication(sys.argv) 57 win = MyWin() 58 win.show() 59 sys.exit(app.exec_())
效果图如下:
不安于小成,然后足以成大器;不诱于小利,然后可以立远功。