Search code examples
pythonpyqt5

Opening a second window PyQt


I have seen other examples of this but they use

class secondWindow():
    def __init__(self):
        super().__init__()
        #some code

class Window():
    def __init__(self):
        super().__init__()
        # some code

def main():
    app = QtGui.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()  

however my code looks like this

class secondWindow():
    def __init__(self):
        some code

class overviewWindow():
    def __init__(self):
        # Database setup
        conn = None
        try:
            conn = sqlite3.connect("exercises.db")
            print("[*] Connected successfully to the database")
        except: 
            print("[*] Error connecting to the databse")

        # Window setup
        self.app = QApplication(sys.argv)
        self.w = QWidget()
        self.w.resize(winWidth, winHeight)
        self.w.move(200, 20)
        self.w.setWindowTitle("Test")
        self.w.setStyleSheet("background-color: #F4F0BB")
        self.w.show()
        
        self.showUI()

        sys.exit(self.app.exec_())


    def showUI(self):
        # Title
        self.title = QLabel() 
        self.title.setParent(self.w)
        self.title.setText("Overblik")
        self.title.resize(winWidth, 100)
        self.title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.title.setStyleSheet("font-size: 45pt")
        self.title.show()

        self.frame = QFrame()
        self.frame.resize(winWidth, 900)
        self.frame.move(0, 100)
        self.frame.setParent(self.w)
        self.frame.show()

        # Buttons
        xBuffer = 130
        yBuffer = 130
        sum = 0
        for i in range(0, 6):
            for j in range(0, 4):
                sum += 1
                self.button2 = Button(self.frame, 75+(j*xBuffer), 75+(i*yBuffer), str(sum))

if __name__ == "__main__":
    overviewWindow()

My problem is i want to open a second window with the same window style (same background and size) as the first but with different content i.e. different labels and buttons

I have tried modifying my code so it looks like the other examples but i cant figure out how to rewrite it without rewriting my entire file.


Solution

  • Try having all your styles and customization in a stylesheet that way you can apply the style to all classes you need to without individually changing elements here is an example:

    from PySide2 import QtCore
    from PySide2.QtWidgets import *
    from PySide2.QtGui import *
    
    
    class Widget2(QWidget):
        def __init__(self, parent=None):
            super(Widget2, self).__init__(parent)
            self.gui()
    
        def gui(self):
            self.w1 = self
            self.w1.setAutoFillBackground(True)
            self.w1.setWindowTitle("")
            self.w1.resize(500, 450)
            self.w1.setCursor(Qt.ArrowCursor)
            self.w1.setToolTip("")
            self.check1 = QCheckBox("Check Box", self.w1)
            self.check1.setChecked(0)
            self.check1.move(180, 220)
            self.check1.resize(90, 22)
            self.check1.setCursor(Qt.ArrowCursor)
            self.check1.setToolTip("")
            self.button2 = QToolButton(self.w1)
            self.button2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            self.button2.setText("Button")
            self.button2.move(40, 110)
            self.button2.resize(90, 22)
            self.button2.setCursor(Qt.ArrowCursor)
            self.button2.setToolTip("")
            return self.w1
    
    
        
        
    class Widget1(QWidget):
        def __init__(self, parent=None):
            super(Widget1, self).__init__(parent)
            self.gui()
    
        def gui(self):
            self.w1 = self
            self.w1.setAutoFillBackground(True)
            self.w1.setWindowTitle("")
            self.w1.resize(500, 450)
            self.w1.setCursor(Qt.ArrowCursor)
            self.w1.setToolTip("")
            self.button1 = QToolButton(self.w1)
            self.button1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            self.button1.setText("Button")
            self.button1.move(40, 110)
            self.button1.resize(90, 22)
            self.button1.setCursor(Qt.ArrowCursor)
            self.button1.setToolTip("")
            self.button1.clicked.connect(self.event)
            return self.w1
    
        def event(self):
            b = Widget2()
            b.setStyleSheet("""
    QToolButton
    {
    color: yellow;
    background-color: red;
    }""")
            b.show()
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        a = Widget1()
        a.setStyleSheet("""
    QToolButton
    {
    color: yellow;
    background-color: red;
    }""")
        a.show()
        sys.exit(app.exec_())
    

    As you can see I have one stylesheet that is applied to both of my QWidgets, ideally you would apply the stylesheet to QApplication but I could not reproduce an example of it working.

    If your window opens and closes straight away try having this in the event function instead:

    def event(self):
    if self.w is None:
        self.w = SecondWindow()
    self.w.show()
    

    Or have self.w = SecondWindow() in the main function and then in the event have the self.w.show().

    So like this:

    class Second(QtGui.QMainWindow):
        some code
     
     
    class First(QtGui.QMainWindow):
        def __init__(self, parent=None):
            some code
            self.w = SecondWindow()
     
        def on_pushButton_clicked(self):
            self.w.show()