PyQt5 - Show QDialog from a different class

user2607702 picture user2607702 · Jul 23, 2016 · Viewed 8.3k times · Source

My app consist of a QMainWindow with a QToolBar. My purpose is to click on a QToolBar element and open in a separate window (QDialog) a calendar.

I want to create in a separate class a QDialog and call it to be shown from the QMainWindow.

This is my QDialog, just a Calendar:

class CalendarDialog(QDialog):

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

Now from a QMainWindow I would like to show the calendar after an action trigger like next:

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

It isn't working. After the event that calls openCalendar the app is closed without printing any output error. I have put some prints to debug and CalendarDialog.__init__(self) isn't even called.

The code regarding to QToolBar is as follow:

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

Answer

Ceppo93 picture Ceppo93 · Jul 24, 2016

The posted code seems almost correct, here a complete working example, I've added some resize to make the widget size "acceptable":

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_()