在 PySide2 中设置垂直和水平对齐方式

Set Vertical and Horizontal alignment in PySide2

QSplashScreen.showMessage()方法接受对齐标志,即 Qt.AlignLeft。设置水平和垂直对齐标志的语法是什么?所有尝试都会产生 "too many variables" 错误。

the Qt5 docs 开始,对齐标志是位字段,因此要将它们组合起来,您可以使用 | 运算符(例如,Qt.AlignLeft | Qt.AlignTop 用于 "top left" 对齐)

Qt::Alignment are QFlags 使用按位运算符 &|^,如果您想组合标志,则必须使用 | 运算符, 在下一部分中我将展示一个例子:

import random
from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    pixmap = QtGui.QPixmap(640, 480)
    h_alignments = (QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignHCenter, QtCore.Qt.AlignJustify)
    v_alignments = (QtCore.Qt.AlignTop, QtCore.Qt.AlignBottom, QtCore.Qt.AlignVCenter, QtCore.Qt.AlignBaseline)
    pixmap.fill(QtGui.QColor("green"))
    w  = QtWidgets.QSplashScreen(pixmap)

    def on_timeout():
        a = random.choice(h_alignments) | random.choice(v_alignments)
        w.showMessage("Stack Overflow", alignment=a)

    timer = QtCore.QTimer(interval=100, timeout=on_timeout)
    timer.start()
    QtCore.QTimer.singleShot(10*1000, QtWidgets.QApplication.quit)
    w.show()
    sys.exit(app.exec_())