2016-07-23 71 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