我想把场景居中对齐。我的问题是,当打开应用程序时,小部件会在某种程度上向下对齐,但在悬停在按钮或标签上后,小部件会居中对齐。有没有什么方法可以解决这个问题?是否有正确的方法来将场景居中对齐于视图中?
这是我应用程序的全部代码:
import sys
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(QSize(1080, 720))
self.setWindowTitle('Graphics Scene')
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.mainview = QGraphicsView(self.centralwidget)
self.mainview.setGeometry(QRect(0, 0, 1080, 720))
alignment = Qt.Alignment(Qt.AlignVCenter, Qt.AlignHCenter)
self.mainview.setAlignment(alignment)
# Main Scene (1)
self.mainScene = QGraphicsScene()
self.mainview.setScene(self.mainScene)
self.labelTitle = QLabel('Main Scene')
self.labelTitle.setStyleSheet('''
QLabel {
font: 48px 'Calibri';
color: #999;
}
''')
styleForButtons = ('''
QPushButton {
margin: 0 70px;
padding: 5px 30px;
}
''')
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.buttonPlay = QPushButton('Play')
self.buttonSettings = QPushButton('Settings')
self.buttonCredits = QPushButton('Credits')
self.buttonMainExit = QPushButton('Exit')
self.buttonPlay.setStyleSheet(styleForButtons)
self.buttonSettings.setStyleSheet(styleForButtons)
self.buttonCredits.setStyleSheet(styleForButtons)
self.buttonMainExit.setStyleSheet(styleForButtons)
self.buttonPlay.setSizePolicy(sizePolicy)
self.buttonSettings.setSizePolicy(sizePolicy)
self.buttonCredits.setSizePolicy(sizePolicy)
self.buttonMainExit.setSizePolicy(sizePolicy)
self.itemLabelTitle = self.mainScene.addWidget(self.labelTitle)
self.itemButtonPlay = self.mainScene.addWidget(self.buttonPlay)
self.itemButtonSettings = self.mainScene.addWidget(self.buttonSettings)
self.itemButtonCredits = self.mainScene.addWidget(self.buttonCredits)
self.itemButtonMainExit = self.mainScene.addWidget(self.buttonMainExit)
self.mainMenuLayout = QGraphicsGridLayout()
self.mainMenuLayout.addItem(self.itemLabelTitle, 0, 0, alignment)
self.mainMenuLayout.addItem(self.itemButtonPlay, 1, 0)
self.mainMenuLayout.addItem(self.itemButtonSettings, 2, 0)
self.mainMenuLayout.addItem(self.itemButtonCredits, 3, 0)
self.mainMenuLayout.addItem(self.itemButtonMainExit, 4, 0)
self.mainMenuWidget = QGraphicsWidget()
self.mainMenuWidget.setLayout(self.mainMenuLayout)
self.mainScene.addItem(self.mainMenuWidget)
def main():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
更新:上传了我所看到的截图。我想要理解为什么我的应用程序表现得如此奇怪:首先,为什么小部件没有完全对齐在中心位置,其次,为什么会有偏移。