PyQt5 QTextBrowser - setText - Alignment issue?

Solution 1:

The problem is caused by the font, in the case of consoles and many IDES use a monospaced font.

For example, if you use the Monospace font:

import numpy as np
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets

def pandas_to_str():
    df = pd.DataFrame({ 
        'A' : 1.,
        'B' : pd.Timestamp('20130102'),
        'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
        'D' : np.array([3] * 4,dtype='int32'),
        'E' : pd.Categorical(["test","train","test","train"]),
        'F' : 'foo' })
    return df.to_string(col_space =14,justify = "justify")

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QTextBrowser()
    w.setStyleSheet('color: blue') 
    w.setFont(QtGui.QFont("Monospace"))
    w.setWordWrapMode(QtGui.QTextOption.NoWrap)
    w.setText(pandas_to_str())
    w.showMaximized()
    sys.exit(app.exec_())

enter image description here