2016-07-23 42 views
0

我的應用由QMainWindowQToolBar組成。我的目的是點擊一個QToolBar元素並在一個單獨的窗口(QDialog)中打開一個日曆。PyQt5 - 顯示不同類別的QDialog

我想創建一個單獨的類QDialog並稱它從QMainWindow顯示。

這是我QDialog,只是一個日曆:

class CalendarDialog(QDialog): 

    def __init__(self): 
     super().__init__(self) 
     cal = QCalendarWidget(self)    

現在從QMainWindow我想顯示的動作觸發條件後,旁邊的日曆:

class Example(QMainWindow): 
    ... 
    calendarAction.triggered.connect(self.openCalendar) 
    ... 
    def openCalendar(self): 
     self.calendarWidget = CalendarDialog(self) 
     self.calendarWidget.show() 

它不工作。在調用openCalendar的事件之後,應用程序關閉而不打印任何輸出錯誤。我已經把一些打印調試,並且CalendarDialog.__init__(self)甚至沒有被調用。

關於向QToolBar的代碼如下:

openCalendarAction = QAction(QIcon(IMG_CALENDAR), "", self) 
openCalendarAction.triggered.connect(self.openCalendar) 
self.toolbar.addAction(openCalendarAction) 
+0

你不是在這行'self.calendarWidget = SMCalendarWidget(self)'創建'CalendarDialog','SMCalendarWidget'是否存在? – Ceppo93

+0

是的,你是對的。這是一個轉錄錯誤。我已更正了代碼。 – user2607702

+0

好的,你可以在「創建」toolBar時分享代碼嗎?提供的似乎幾乎是正確的,除了'CalendarDialog .__ init __(self)'不帶任何參數(self是隱含的),並且你用一個參數調用它'CalendarDialog(self)',可能你想指定一個'parent'參數'__init__'。 – Ceppo93

回答

0

張貼的代碼似乎是正確的,在這裏一個完整的工作示例中,我添加了一些resize,使部件尺寸「可接受」:

from PyQt5.QtGui import * 
from PyQt5.QtWidgets import * 


class CalendarDialog(QDialog): 

    def __init__(self, parent): 
     super().__init__(parent) 
     self.cal = QCalendarWidget(self) 

     self.resize(300, 300) 
     self.cal.resize(300, 300) 

class Example(QMainWindow): 

    def __init__(self): 
     super().__init__() 
     self.resize(400, 200) 

     toolBar = QToolBar(self) 

     calendarAction = QAction(QIcon('test.png'), 'Calendar', self) 
     calendarAction.triggered.connect(self.openCalendar) 
     toolBar.addAction(calendarAction) 

    def openCalendar(self): 
     self.calendarWidget = CalendarDialog(self) 
     self.calendarWidget.show() 


app = QApplication([]) 

ex = Example() 
ex.show() 

app.exec_() 
+0

您的解決方案完美:D謝謝!現在我正在嘗試將'CalendarDialog'移動到一個不同的.py文件,並且它不起作用......你有一個想法,爲什麼? – user2607702

+0

任何錯誤?你正在執行正確的文件(帶有'app.exec _()')的文件嗎? – Ceppo93

+0

事情是,大綱中沒有顯示任何錯誤...應用程序剛剛關閉...我正在考慮我的導入...我創建了一個新包'main.widgets',在這裏我找到了'CalendarDialog .py'。要導入它:'從main.widgets導入CalendarDialog'是對的? – user2607702