用PyQt5库,就是qt在python语言环境的库。通过库提供的qt接口实现写对联这个事情。
对联画布使用QWidgets。长宽设置为self.resize(550,550) 。
接着使用hBoxLayout = QtWidgets.QHBoxLayout(),添加左联、横批和右联。
hBoxLayout = QtWidgets.QHBoxLayout()
hBoxLayout.addWidget(leftSide)
hBoxLayout.addWidget(middleSide)
hBoxLayout.addWidget(rightSide)
首先我们会构建一个对联class需要的元素,代码里我命名为MyLabel。
painter.setFont(QFont('楷体', font_size))
,字号font_size=30
coor_orig_x =20
,coor_orig_y =100
painter的painter.drawText(QRectF())
,的第一个参数一定是用Rect,如果不是Rect,即使加了换行符也没用painter.fillRect(QRectF(coor_orig_x,coor_orig_y,font_size,coor_orig_y+font_size*7), QtGui.QColor(230,0,0))
,横联通过painter.fillRect(QRectF(0,0,font_size*4,font_size+10), QtGui.QColor(230,0,0))
painter.setPen(QtCore.Qt.black)
完整的程序如下,或者在这里github链接https://github.com/lumanyu/ai_app/blob/main/spring_couplets/couplets.py下载:
import sys
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import QRectF
class MyLabel(QtWidgets.QWidget):
def __init__(self, text=None, horizontal=False):
super(self.__class__, self).__init__()
self.text = text
#self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
#self.setStyleSheet("background-color: {};".format(QtGui.QColor(230, 0, 0).name()))
self.horizontal=horizontal
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.setPen(QtCore.Qt.black)
font_size=30
painter.setFont(QFont('楷体', font_size)) #对联使用的字体和大小
coor_orig_x = 20
coor_orig_y = 100
if self.horizontal:
painter.translate(0, font_size*4/2) #平移到label的相对坐标(0,60)
else:
painter.translate(coor_orig_x, coor_orig_y) #平移到lable的相对坐标(20,100)
#painter.rotate(-90)
if self.text:
#painter.drawText(QRectF(0.0,0.0,50.0,500.0), QtCore.Qt.AlignCenter, 0, 0, self.text)
if self.horizontal:
painter.fillRect(QRectF(0,0,font_size*4,font_size+10), QtGui.QColor(230, 0, 0))
painter.drawText(0, font_size, self.text)
else:
painter.fillRect(QRectF(coor_orig_x,coor_orig_y,font_size,coor_orig_y+font_size*7), QtGui.QColor(230, 0, 0))
painter.drawText(QRectF(coor_orig_x,coor_orig_y,font_size,coor_orig_y+font_size*7), self.text)
painter.end()
class Example(QtWidgets.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
leftSide = MyLabel("桃\n花\n坞\n里\n桃\n花\n庵")
middleSide = MyLabel('桃花庵歌', horizontal=True)
rightSide = MyLabel('桃\n花\n庵\n下\n桃\n花\n仙')
hBoxLayout = QtWidgets.QHBoxLayout()
hBoxLayout.addWidget(leftSide)
hBoxLayout.addWidget(middleSide)
hBoxLayout.addWidget(rightSide)
self.setLayout(hBoxLayout)
self.setGeometry(300, 300, 250, 150)
self.resize(550, 550) #对联画布宽高
self.show()
def main():
app = QtWidgets.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
效果如下:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。