【问题标题】:PyQt5 QTextBrowser - setText - Alignment issue?PyQt5 QTextBrowser - setText - 对齐问题?
【发布时间】:2019-05-21 21:00:20
【问题描述】:

我正在尝试使用 PyQt5 制作一个简单的 GUI 控制台。在尝试使用 QTextBrowser - setText 打印文本时,它会失去对齐并且看起来很糟糕。但是文本在我的 python 控制台中是对齐的

我正在使用 setText 函数来显示我的数据框。 在更改 df.to_string() 的 justify 参数时,我可以在 python 控制台中看到更改后的对齐方式,但这并没有反映在我的 Qt 控制台中。

代码:

import sys
from GUI_4 import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
import New_Read_Map_File

def window():    
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QWidget()   
    label = QtWidgets.QTextBrowser(MainWindow)                    
    label.setStyleSheet('color: blue')    
    MainWindow.setGeometry(600,150,800,800)
    label.setGeometry(10,10,780,780)    
    GetData()
    label.setText(DisplayData)
    MainWindow.show()
    sys.exit(app.exec_())    

def GetData():
    global DisplayData
    New_Read_Map_File.read_MapFile_main()
    DisplayData = (New_Read_Map_File.df.to_string(col_space = 14,justify = "justify"))    
    print(DisplayData)


window()

预期对齐方式

观察到的 Qt GUI

【问题讨论】:

    标签: python pyqt pyqt5 qtextbrowser


    【解决方案1】:

    问题是由字体引起的,在控制台和许多 IDES 的情况下使用monospaced 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_())
    

    【讨论】:

    • 感谢您的回复和编辑 eyllanesc,我尝试更改字体..仍然,问题仍然存在。
    • 我已经按照您的建议尝试了 Monospace。此外,使用代码中的对齐选项 QtGui.QTextOption.NoWrap 。没有效果。然后,我尝试使用 Arial。我可以看到更改后的字体..但对齐仍然损坏...感谢您的大力支持... :)
    • 非常感谢......正如你所提到的,问题是没有安装字体。我从你的 github 链接中调整了字体,它运行得很快........你太棒了..!! - 帕万
    • 能否提供有关如何安装字体的信息,我没有看到 github 链接
    猜你喜欢
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2016-02-18
    • 2013-01-07
    相关资源
    最近更新 更多