gpt4 book ai didi

python - QMainWindow 中的布局错误?

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:51 28 4
gpt4 key购买 nike

我在 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)

最佳答案

当您将父级传递给 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)

完整代码:

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 central widget, create grid layout
centralWidget = Main(self)
self.setCentralWidget(centralWidget)

屏幕截图:

enter image description here

关于python - QMainWindow 中的布局错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44918165/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com