如何解决我试图让两个QFrame占用QMainWindow的一半强制偏移,我似乎无法摆脱它
我只是在尝试PyQt5,所以我可以找出我正在编写的另一个程序中的一些问题,但是最大的事情是我似乎无法弄清楚如何精确地改变小部件的几何形状。
我用两个不同颜色的框架编写了这个小测试窗口,并试图将它们分割成整个可能的空间。
class Test(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Test")
self.setGeometry(QRect(QPoint(300,300),QSize(300,300)))
self._centralWidget = QWidget()
self._centralLayout = QHBoxLayout()
self.setCentralWidget(self._centralWidget)
self._centralWidget.setLayout(self._centralLayout)
self.initGUI()
self.show()
def initGUI(self):
self.leftFrame = QFrame()
self.leftFrame.setStyleSheet("background-color:red")
self.leftFrame.setGeometry(QRect(QPoint(0,0),QSize(150,300))) # Same as QRect(0,150,300)
self.rightFrame = QFrame()
self.rightFrame.setStyleSheet("background-color:green")
self.rightFrame.setGeometry(QRect(QPoint(150,300))) # Same as QRect(150,300)
self._centralLayout.addWidget(self.leftFrame)
self._centralLayout.addWidget(self.rightFrame)
MainWindow是300x300,所以我将两个帧设置为150x300。但是,当我运行它时,会有一个令人讨厌的偏移量9x9。因此,这两个框架的真实大小是:左框架:QRect(9,9,138,282)
|右框:QRect(153,282)
。
我怀疑可能是QHBoxLayout弄乱了尺寸,但我不确定。任何建议表示赞赏!
解决方法
如果您要手动设置几何图形,则不应使用布局,因为布局的目的是根据其特征自动处理它们。
def initGUI(self):
self.leftFrame = QFrame(self._centralWidget)
self.leftFrame.setStyleSheet("background-color:red")
self.leftFrame.setGeometry(QRect(QPoint(0,0),QSize(150,300)))
self.rightFrame = QFrame(self._centralWidget)
self.rightFrame.setStyleSheet("background-color:green")
self.rightFrame.setGeometry(QRect(QPoint(150,300)))
如果要使用布局,则不必在QFrame中使用setGeometry,还必须将布局的边距和间距设置为0:
def initGUI(self):
self.leftFrame = QFrame()
self.leftFrame.setStyleSheet("background-color:red")
self.rightFrame = QFrame()
self.rightFrame.setStyleSheet("background-color:green")
self._centralLayout.addWidget(self.leftFrame)
self._centralLayout.addWidget(self.rightFrame)
self._centralLayout.setContentsMargins(0,0)
self._centralLayout.setSpacing(0)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。