Python game engine development: TextField text

Source: Internet
Author: User
Tags drawtext getcolor

Python game engine development: TextField text

 

TextField

Anyone who has used flash knows that this class is not only used to display text, but also used to display input boxes. I will only implement some basic and practical functions here, and it will take some time to expand. Like the previous chapter,TextFieldIs a display object inherited fromDisplayObject. The following code is used:

class TextField(DisplayObject):    def __init__(self):        super(TextField, self).__init__()        self.text =         self.font = Arial        self.size = 15        self.textColor = #000000        self.italic = False        self.weight = TextFormatWeight.NORMAL    def _getOriginalWidth(self):        font = self.__getFont()        fontMetrics = QtGui.QFontMetrics(font)        return fontMetrics.width(str(self.text))    def _getOriginalHeight(self):        font = self.__getFont()        fontMetrics = QtGui.QFontMetrics(font)        return fontMetrics.height()    def __getFont(self):        weight = self.weight        if self.weight == TextFormatWeight.NORMAL:            weight = QtGui.QFont.Normal        elif self.weight == TextFormatWeight.BOLD:            weight = QtGui.QFont.Bold        elif self.weight == TextFormatWeight.BOLDER:            weight = QtGui.QFont.Black        elif self.weight == TextFormatWeight.LIGHTER:            weight = QtGui.QFont.Light        font = QtGui.QFont()        font.setFamily(self.font)        font.setPixelSize(self.size)        font.setWeight(weight)        font.setItalic(self.italic)        return font    def _loopDraw(self, c):        font = self.__getFont()        flags = QtCore.Qt.AlignCenter        width = self.width        height = self.height        pen = QtGui.QPen()        pen.setColor(getColor(self.textColor))        c.setFont(font)        c.setPen(pen)        c.drawText(0, 0, width, height, flags, str(self.text))

In this class, we define some attributes related to text display. The following describes these attributes:

The text displayed in text is strThe object font text font is also strObject, such as: "text" textColor text color, strType, for example, "red" size text size, intType. The default unit is whether the px italic text is the width of the italic weight text.

Because this class is inherited fromDisplayObjectSo, in addition to the above attributes, you can also useDisplayObjectAll non-private properties in, suchx,y,rotation.

Now start code analysis. First, let's look at the painting part._loopDrawMethod. First__getFontObtain a font. The resulting font isQFontObject that contains all the attributes related to the text font style, such as the font, text size, and text width we set. You can browse__getFontTo understand this.
You may not understand the three variables (flag,width,height). This is actually related to the way the text is drawn. Qt draws text by first giving a range of drawn text, and then giving the alignment of the drawn text to the rectangle, that isflagVariable (in Qt|To connect the left, right, and up and down alignment modes, suchflag = QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottomIn the codeQtCore.Qt.AlignCenterIndicates the center and alignment of both the upper and lower sides ).
It is not difficult to understand the principles of painting.QPainterOfdrawTextMethod. The first four parameters are used to determine the horizontal and vertical coordinates and width and height of the drawn text range, 5th are alignment, and 6th are displayed text content.
There is anotherQPenThe object is not described. In Qt, the painting tool is divided into pen and brush, pen is used for stroke, and brush is used for filling. Text display is a stroke, so you can set a pen to control the color and other styles of the Text object.QPenThe object is used to implement the pen.
_getOriginalWidthAnd_getOriginalHeightAs mentioned in the previous article, it is used to determine the object size. Qt providesQFontMetricsClass to determine the text width and height under a certain field. It is worth noting that in the width and height test, the height measurement has nothing to do with the text content, but only with the font. For specific usage instructions, see the code.

AndTextFormatWeightThis class is a static class used to hold some constants about the font width:

class TextFormatWeight(Object):    NORMAL = normal    BOLD = bold    BOLDER = bolder    LIGHTER = lighter    def __init__(self):        raise Exception(TextFormatWeight cannot be instantiated.)
Hello World Applet

With the above encapsulation, you can complete the Hello World Applet:

from pylash import init, addChild, TextFielddef main():    txt = TextField()    # set the content of the text field    txt.text = Hello World    # set color of text    txt.textColor = red    # set position    txt.x = 50    txt.y = 100    # set size    txt.size = 50    # add text field into display list    addChild(txt)# parameters: refreshing speed, window title, window width, window height, callbackinit(30, Hello World, 800, 600, main)

:

The encapsulated code:

class TextField(DisplayObject):    def __init__(self):        super(TextField, self).__init__()        self.text =         self.font = Arial        self.size = 15        self.textColor = #000000        self.italic = False        self.weight = TextFormatWeight.NORMAL    def _getOriginalWidth(self):        font = self.__getFont()        fontMetrics = QtGui.QFontMetrics(font)        return fontMetrics.width(str(self.text))    def _getOriginalHeight(self):        font = self.__getFont()        fontMetrics = QtGui.QFontMetrics(font)        return fontMetrics.height()    def __getFont(self):        weight = self.weight        if self.weight == TextFormatWeight.NORMAL:            weight = QtGui.QFont.Normal        elif self.weight == TextFormatWeight.BOLD:            weight = QtGui.QFont.Bold        elif self.weight == TextFormatWeight.BOLDER:            weight = QtGui.QFont.Black        elif self.weight == TextFormatWeight.LIGHTER:            weight = QtGui.QFont.Light        font = QtGui.QFont()        font.setFamily(self.font)        font.setPixelSize(self.size)        font.setWeight(weight)        font.setItalic(self.italic)        return font    def _loopDraw(self, c):        font = self.__getFont()        flags = QtCore.Qt.AlignCenter        width = self.width        height = self.height        pen = QtGui.QPen()        pen.setColor(getColor(self.textColor))        c.setFont(font)        c.setPen(pen)        c.drawText(0, 0, width, height, flags, str(self.text))class TextFormatWeight(Object):    NORMAL = normal    BOLD = bold    BOLDER = bolder    LIGHTER = lighter    def __init__(self):        raise Exception(TextFormatWeight cannot be instantiated.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.