我想在中间对齐场景。我的问题是,当你打开一个应用程序时,小部件会以某种方式在中间位置对齐,但是在将鼠标悬停在按钮或标签上之后,小部件会在中间对齐。我能以某种方式修复此问题吗?有没有正确的方法来对齐视图中间的场景?
这是我的应用程序的整个代码:
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()
UPD:上传我看到的截图
我想理解为什么我的应用程序行为如此奇怪:首先,为什么小部件不完全在中心对齐,其次,为什么有一个转移
问题是因为场景没有设置sceneRect()
所以当显示QGraphicsView
时,它使用屏幕的分辨率作为基础设置场景的大小,因此它最初可以具有所有项目的boundingRect()
的大小这是相对于那个大小居中而不是相对于viewport()
中显示的场景部分,只是在用鼠标经过场景之后调用update()
方法并且它更新为正确的大小。因此,一种解决方案是使用场景坐标中窗口小部件的大小来设置sceneRect()
。
self.mainScene.setSceneRect(QRectF(QPointF(), self.mainMenuWidget.sizeHint(Qt.PreferredSize)))
self.mainScene.addItem(self.mainMenuWidget)