2017-02-09 178 views
0

子窗口無法工作,如何使用類在主窗口中嵌入一個窗口:顯示在主窗口

#!/usr/bin/python3 
# -*- coding: utf-8 -*- 

""" 
Qt4 tutorial using classes 

This example will be built 
on over time. 
""" 

import sys 
from PyQt4 import QtGui, QtCore 

class Form(QtGui.QWidget): 

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


class MainWindow(QtGui.QMainWindow): 

    def __init__(self, parent=None): 
     super(MainWindow, self).__init__() 
     self.setGeometry(50, 50, 1600, 900) 
     new_window = Form(self) 
     self.show() 


def main(): 
    app = QtGui.QApplication(sys.argv) 
    main_window = MainWindow() 
    sys.exit(app.exec_())  

if __name__ == "__main__": 
    main() 

這應該是使用類的代碼的最根本一點。我如何獲得第二個窗口來顯示請。

+0

你是什麼意思的窗口?彈出的對話框或主GUI中的小部件? – alexblae

+0

道歉,我正試圖讓主窗口上出現一個框。它在類Form中,但我不能顯示它,我可以在主窗口上放一個按鈕並讓它彈出,但我想要嵌入。 – iFunction

+0

'Form'沒有父項,你沒有把它放在佈局中,也沒有'show()'它。 – ekhumoro

回答

1

由於ekhumoro已經指出,您的小部件必須是您的mainWindow的子項。但是,我認爲您不需要爲該窗口小部件調用show,因爲無論如何只要其父節點(MainWindow)調用show就會被調用。正如mata指出的那樣,將Widget添加到MainWindow實例的正確方法是使用setCentralWidget。這裏是一個澄清的工作示例:

import sys 
from PyQt4 import QtGui, QtCore 

class Form(QtGui.QWidget): 

    def __init__(self, parent): 
     super(Form, self).__init__(parent) 
     self.lbl = QtGui.QLabel("Test", self) 

class MainWindow(QtGui.QMainWindow): 

    def __init__(self, parent=None): 

     super(MainWindow, self).__init__() 
     self.setGeometry(50, 50, 1600, 900) 
     new_window = Form(self) 
     self.setCentralWidget(new_window) 
     self.show() 

def main(): 
    app = QtGui.QApplication(sys.argv) 
    main_window = MainWindow() 
    sys.exit(app.exec_())  

if __name__ == "__main__": 
    main() 
+0

不,這不是正確的方式來使用QMainWindow,添加內容到它的['setCentralWidget()'](http://doc.qt.io/qt-5/qmainwindow.html#setCentralWidget)方法應該是用過的。 – mata

+0

你說得對,我只是不確定[iFunction](http://stackoverflow.com/users/6500048/ifunction)是否需要「Form」作爲「centralWidget」。 – alexblae

+0

@alexblae。我的意思是,爲了使窗口小部件可見,你至少需要做一件我提到的事情。將其設置爲中心控件與將其添加到佈局效果相同 - 在這種情況下,不需要顯式設置父控件(因爲它會自動重新設置)。 – ekhumoro