带有空格的 PyQt 等长字符串具有不同的显示长度

PyQt equal length strings with whitespaces have different display length

PyQt5中,我发现带空格的等长字符串最终显示长度不同:

所需的输出 应该是这样的:

123456789
1 3456789
1  456789
1   56789

我发现这个问题不仅存在于QComboBox,也存在于其他多行小部件中。固定长度,例如 {:15s},也会导致问题。

有没有办法显示成想要的输出?

所描述问题的一个最小示例:

from PyQt5.QtWidgets import QApplication, QComboBox, QMainWindow
import sys

class Window(QMainWindow):
    def __init__(self): 
        super().__init__() 
        self.combo_box = QComboBox(self)
        a = ["123456789", "1 3456789", "1  456789", "1   56789"]
        self.combo_box.addItems(a)
        self.show()

App = QApplication(sys.argv) 
window = Window()
sys.exit(App.exec())

错位是由字体引起的,因为它不会在字母和 space 之间为您提供相同的 space。解决方案是使用像“monospace”这样的字体:

from PyQt5.QtGui import QFont

font = QFont("monospace")
self.combo_box.setFont(font)