2017-07-05 34 views
0

我在PyQT5中弄錯了佈局。我究竟做錯了什麼?是否有一些預定義的小場或相似?我創建了主窗口作爲QMainWindow,並在其內部創建了一個小部件作爲中心部件。這是它的樣子:PyQT5錯誤的佈局?

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) 
+0

看到我的回答:P – eyllanesc

回答

1

當您通過父一個QWidget這將找到的位置相對於其父併產生像你已經獲得的那些部件,來解決這個,佈局被使用,QMainWindow的是一種特殊的QWidget,因爲它具有預定的元素,所以它已經具有一個佈局:

enter image description here

在QMainWindow的微件必須被添加到該centralwidget機智小時setCentralWidget功能,在您的情況:

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

+0

現在很清楚。它是QMainWindow或QWidget與我的自定義佈局。感謝QMainWindow的額外解釋。 –