QMainWindow中的布局错误?

2024-10-01 17:38:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在PyQT5得到了错误的布局。我做错什么了?是否有一些预定义的小字段大小或类似大小?我将主窗口创建为QMainWindow,并在其中创建一个小部件作为中心小部件。它看起来是这样的:

enter image description here

class Main(QWidget):
    """The main widget with label and LineEdit"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize the UI of the main widget"""
        self.mySourceLabel = QLabel("Select your file:")
        self.mySourceLine = QLineEdit()
        self.mySourceLine.setPlaceholderText("File name here")

        # Set layout
        grid = QGridLayout()
        #grid.setSpacing(5)
        grid.addWidget(self.mySourceLabel, 0, 0)
        grid.addWidget(self.mySourceLine, 1, 0)
        self.setLayout(grid)

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize UI of an application"""
        # main window size, title
        self.setGeometry(400, 300, 400, 300)
        self.setWindowTitle("Version upgrade ")

        # create instance of a class Main
        self.main = Main(self)

        # create central widget, create grid layout
        centralWidget = QWidget()
        centralLayout = QGridLayout()
        centralWidget.setLayout(centralLayout)

Tags: ofselfinitmain部件defcreatewidget
1条回答
网友
1楼 · 发布于 2024-10-01 17:38:21

当您将父对象传递给一个QWidget时,它将定位相对于其父对象的位置,并生成与您获得的类似的窗口小部件,为了解决这个问题,使用布局,QMainWindow是一个特殊的QWidget,因为它有预定义的元素,所以它已经有了布局:

enter image description here

在QMainWindow中,必须使用setCentralWidget函数将小部件添加到centralwidget,在您的示例中:

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        [...]
        centralWidget = Main(self)
        self.setCentralWidget(centralWidget)

完整代码:

^{pr2}$

截图:

enter image description here

相关问题 更多 >

    热门问题