Rotate Text (PySide)

vegaseat 2 Tallied Votes 2K Views Share

Just the very basics on how to draw a rotated text using the Python GUI toolkit PySide (public PyQt). Please experiment and embellish.

""" ps_draw_text_rotated.py
draw a rotated text with PySide's QPainter class

download PySide (LGPL-licensed version of PyQT) from:
http://qt-project.org/wiki/PySide
or Windows binary from:
http://www.lfd.uci.edu/~gohlke/pythonlibs/

tested with Python27/34 and PySide122   by  vegaseat  26oct2014
"""

from PySide.QtCore import *
from PySide.QtGui import *


class MyWindow(QWidget):

    def __init__(self, text, degrees):
        # QWidget will be self
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        # upper left corner coordinates (x_pos, y_pos)
        self.setGeometry(300, 100, 520, 520)
        self.setWindowTitle('Testing text rotation ...')
        self.text = text
        self.degrees = degrees

    def paintEvent(self, event):
        '''
        the method paintEvent() is called automatically
        the QPainter class does the low-level painting
        between its methods begin() and end()
        '''
        qp = QPainter()
        qp.begin(self)
        # set text color, default is black
        qp.setPen('red')
        # QFont(family, size)
        qp.setFont(QFont('Decorative', 12))
        # start text at point (x, y)
        x = 30
        y = 30
        qp.translate(x, y)
        qp.rotate(self.degrees)
        qp.drawText(0, 0, self.text)
        qp.end()


text = '''\
You pass an elementary school playground and the
children are all busy with their cellphones.
'''

# for command line replace [] with sys.argv
app = QApplication([])
# degrees of text rotation (clockwise)
degrees = 45
win = MyWindow(text, degrees)
win.show()
# run the application event loop
app.exec_()
sneekula 969 Nearly a Posting Maven

Works well, wonder why you need function translate()?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Simply try it without translate.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.