代码让qpushbutton的文字在垂直方向居中
可以使用QHBoxLayout和QVBoxLayout来实现QPushButton的文字在垂直方向居中。
示例代码如下:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
button = QPushButton('Button')
layout = QVBoxLayout()
layout.addWidget(button)
layout.setAlignment(button, Qt.AlignCenter) # 设置按钮在垂直方向居中
self.setLayout(layout)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Centered Button')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
在这个示例中,我们创建了一个QPushButton,并使用QVBoxLayout将其添加到QWidget上。然后,我们使用layout.setAlignment(button, Qt.AlignCenter)将按钮在垂直方向上居中对齐。最后,我们将QWidget设置为窗口的布局,并显示窗口。
注意:在这个示例中,我们使用的是PyQt5库。如果你使用的是PyQt4库,需要将from PyQt5.QtWidgets改为from PyQt4.QtGui
原文地址: https://www.cveoy.top/t/topic/iRH9 著作权归作者所有。请勿转载和采集!