QMainWindow和子窗口小部件的大小不匹配

时间:2016-02-09 19:44:43

标签: qt layout pyqt pyside qmainwindow

可能是一个菜鸟问题,但我还在学习PySide。所以我尝试使用QMainWindow,它有一个QFrame,而QFrame有两个标签。我在QMainWindow和QFrame上使用QBoxLayouts。问题是,当我将QFrame设置为200x200之类的时候,QMainWindow不会调整大小,它仍然太小而无法显示两个标签。如果我错了,请纠正我,但在使用布局时,QMainWindow是否应该自动拥有合适的尺寸?另外,当我输出frame.sizeHint()然后输出PySide.QtCore.QSize(97, 50)但我希望它是200,200。

以下代码将重现问题:

import sys
from PySide import QtGui


class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        self.initUI()

    def initUI(self):

        #-------
        #CREATE WIDGETS
        #-------
        frame = QtGui.QFrame()
        frame.setStyleSheet("QFrame {background-color: yellow}")
        frame.setGeometry(0, 0, 200, 200)

        someLabel = QtGui.QLabel("SomeLabel")
        someOtherLabel = QtGui.QLabel("SomeOtherLabel")

        self.setCentralWidget(frame)

        #--------
        #CREATE LAYOUT
        #--------

        frameLayout = QtGui.QVBoxLayout()
        frameLayout.addWidget(someLabel)
        frameLayout.addWidget(someOtherLabel)
        frame.setLayout(frameLayout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(frame)
        self.setLayout(mainLayout)

        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

运行代码后会发生这种情况:

enter image description here

1 个答案:

答案 0 :(得分:3)

QMainWindow已有顶级布局,因此您不应自行设置。您需要做的就是设置central-widget,然后为其添加布局和小部件。

因此可以修改您的示例:

    frame.setLayout(frameLayout)

    # get rid of these three lines
    # mainLayout = QtGui.QVBoxLayout()
    # mainLayout.addWidget(frame)
    # self.setLayout(mainLayout)

    self.show()

值得注意的是,PySide中可能存在关于此问题的错误/错误,因为在PyQt中,您的原始脚本会打印一条有用的错误消息:

  

QWidget :: setLayout:尝试在MainWindow上设置QLayout“”,已经有布局

相关问题