0

My setup is Windows 10, Python 3.7, PyQt5

The goal is to print a formatted table to a QPlainTextEdit.

I have some data in a PrettyTable object. When I print this data to stdout, the table gets printed perfectly! But when printing to QPlainTextEdit (using table.get_string())... it looses the correct format.

A small code to show the issue:

import sys

from PyQt5.QtWidgets import (
    QApplication, QLabel, QPlainTextEdit, QVBoxLayout, QWidget)
from prettytable import PrettyTable

class Example(QWidget):

def __init__(self):
    super().__init__()

self.initUI()

def initUI(self):
    hbox = QVBoxLayout(self)

qpt = QPlainTextEdit(self)
qpt.setReadOnly(True)

x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_rows(
    [
        ["Adelaide", 1295, 1158259, 600.5],
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Darwin", 112, 120900, 1714.7],
        ["Hobart", 1357, 205556, 619.5],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
    ]
)
qpt.appendPlainText(x.get_string())

hbox.addWidget(qpt)

self.resize(400, 300)
self.setWindowTitle('QPlainTextEdit')
self.show()

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

enter image description here

How to achieve the correct format for the table?

1 Answers1

0

Found the answer in this post.

Keeping it short:

font = QFont("Monospace")
font.setStyleHint(QFont.TypeWriter)
my_plain_text_edit.setFont(font)