2012-11-09 30 views
0

需要基本的幫助,基本上我有一個菜單欄和一些選項的主窗口。當我點擊其中一個選項時,我的代碼應該打開另一個窗口。我的代碼現在看起來像這樣。 所有必需的庫都被導入。PyQt4中

class subwindow(self): 
    //Another small window 

class MainWindow(QtGui.QMainWindow): 
    def __init__(self): 
     super(MainWindow , self).__init__()  
     self.window() 

    def window(self): 
     Action = QtGui.QAction(QtGui.QIcon('action.png') , 'action' , self)   
     Action.triggered.connect(self.a) 

     mb = self.menuBar() 
     option = mb.addMenu('File') 
     option.addAction(Action) 

     self.show() 

    def a(self): 
     s = subwindow() 



if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 
    mw = MainWindow() 
    sys.exit(app.exec_()) 

如何運行代碼的子窗口部分。如何添加QtGui.QApplication部分?

+0

你做*不*必須創建一個'QApplication'每一個窗口。這裏必須只有一個'QApplication',所以你只需要創建子窗口,並調用'show'方法。 – Bakuriu

回答

1

就像@Bakuriu說,在評論中,有且只有一個QApplication的實例。這將啓動應用程序的主事件循環。

您可以通過派生從QDialog的類的子窗口類,並自定義它,只要你想創建一個新窗口。 你需要調用QDialog的類的exec_()方法來獲取對話框顯示。

例如,在你的代碼:

from PyQt4 import QtGui 
import sys 

class SubWindow(QtGui.QDialog): 
    def __init__(self): 
     super(SubWindow , self).__init__()  
     label = QtGui.QLabel("Hey, subwindow here!",self); 

class MainWindow(QtGui.QMainWindow): 
    def __init__(self): 
     super(MainWindow , self).__init__()  
     self.window() 

    def window(self): 
     Action = QtGui.QAction(QtGui.QIcon('action.png') , 'action' , self)   
     Action.triggered.connect(self.a) 

     mb = self.menuBar() 
     option = mb.addMenu('File') 
     option.addAction(Action) 

     self.show() 

    def a(self): 

     s = SubWindow() 
     s.exec_() 

if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 
    mw = MainWindow() 
    sys.exit(app.exec_()) 
1

當你想在Qt的應用程序,並在像GTK許多GUI應用程序打開的窗戶子,以及,你打開一個對話框。下面的例子可以告訴你如何做到這一點。它有一個主窗口,它有一個菜單,可以打開對話框並詢問你的名字。它使用在對話框中建,如果你想自定義對話框,它包含可以檢查出Create a custom dialog什麼。有關創建對話框而不是另一個QMainWindow的討論,請查看Multiple Windows in PyQt4

import sys 
from PyQt4 import QtGui 

class MainWindow(QtGui.QMainWindow): 
    def __init__(self): 
     super(MainWindow, self).__init__() 
     action = QtGui.QAction(QtGui.QIcon('action.png'), '&New Window', self) 
     action.triggered.connect(self.new_win) 
     self.menuBar().addMenu('&File').addAction(action) 
     self.setGeometry(300, 300, 300, 200) 
     self.show() 

    def new_win(self): 
     name, ok = QtGui.QInputDialog.getText(self, 'Input', 'Enter name:') 
     print name, ok 

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