2017-01-09 31 views
0

我想在GUI應用程序中獲取按鈕和菜單欄。當我運行我的代碼時,GUI出現在菜單欄中,但沒有看到按鈕。這是我的示例代碼。代碼編譯時沒有任何錯誤。用PySide開發一個GUI

import sys 
from PySide.QtGui import * 
from PySide.QtCore import * 

class guiwindow(QMainWindow): 

    def __init__(self): 
     super(guiwindow,self).__init__() 

     self.menubar() 

    def menubar(self): 
     textEdit = QWidget() 
     self.setCentralWidget(textEdit) 

     exitAction = QAction('Exit', self) 
     exitAction.setShortcut('Ctrl+Q') 
     exitAction.setStatusTip('Exit application') 
     exitAction.triggered.connect(self.close) 

     self.statusBar() 

     menubar = self.menuBar() 
     fileMenu = menubar.addMenu('&File') 
     fileMenu.addAction(exitAction) 

     self.setGeometry(400, 100, 1200, 800) 
     self.setWindowTitle("Menubar + Buttons") 


     button = QPushButton("Test") 
     hbox = QHBoxLayout() 
     hbox.addStretch(1) 
     hbox.addWidget(button) 
     self.setLayout(hbox) 
     self.show() 


def main(): 
    app = QApplication(sys.argv) 
    ex = guiwindow() 
    sys.exit(app.exec_()) 


if __name__ == '__main__': 
    main() 

回答

0

一般來說,在GUI編程中,你將不得不忽視父類和子類小部件的概念。如果你想讓你的按鈕進入你的窗戶,那麼後者應該是前者的孩子。

所以使用:

button = QPushButton("Test", parent=self) 

相反的:

button = QPushButton("Test") 

希望這有助於!

+0

請問您可以告訴我一些很好的教程/文檔,以瞭解更多信息。這可以工作,但出現的按鈕似乎在菜單欄的文件選項上重疊。謝謝您的回答。 –

+0

@RaghavendraMG這可能是因爲你需要將佈局設置爲中央部件而不是主窗口(這是Qt所不允許的)。所以它應該是'textEdit.setLayout(hbox)'而不是'self.setLayout(hbox)'。不過考慮用'centralWidget'之類的東西改變'textEdit'。 – cdonts