Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

python - PyQt, how can I connect button?

I have a login form and I want to connect the button to another window. So here is my code but when I run it, it shows the login window but after I clicked the button the next window only shows up for a moment. I tried multiple times after watching here and there but it didn't work out.

class Login(QMainWindow):
      def __init__(self):
          super().__init__()

          self.setGeometry(750, 350, 400, 225)
          self.setWindowTitle('Login')

          #stuff right here

          self.tombol = QPushButton('Login', self)
          self.tombol.setGeometry(225, 150, 101, 23)
          self.tombol.clicked.connect(Main)
          self.show()

 class Main(QMainWindow):
      def __init__(self):
          super().__init__()

          self.setGeometry(750, 350, 400, 150)
          self.setWindowTitle('Hasil Pilkada')

          #stuff right here too

          self.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is simple: Main is created with a limited scope, so a moment later it will be eliminated, so the window is seen in a single moment.

The objective could be rewritten as: when the button is pressed then the other window must be shown, for the user it is indifferent if it is created before the window or not but only shown.

class Login(QMainWindow):
      def __init__(self):
          super().__init__()

          self.other_window = Main()

          self.setGeometry(750, 350, 400, 225)
          self.setWindowTitle('Login')

          #stuff right here

          self.tombol = QPushButton('Login', self)
          self.tombol.setGeometry(225, 150, 101, 23)
          self.tombol.clicked.connect(self.other_window.show)
          self.show()

 class Main(QMainWindow):
      def __init__(self):
          super().__init__()

          self.setGeometry(750, 350, 400, 150)
          self.setWindowTitle('Hasil Pilkada')

          #stuff right here too

          # self.show()

Another way where if the window is created and shown:

class Login(QMainWindow):
      def __init__(self):
          super().__init__()

          self.setGeometry(750, 350, 400, 225)
          self.setWindowTitle('Login')

          #stuff right here

          self.tombol = QPushButton('Login', self)
          self.tombol.setGeometry(225, 150, 101, 23)
          self.tombol.clicked.connect(self.handle_clicked)
          self.show()

    def handle_clicked(self):
        if not hasattr(self, "other_window"):
            self.other_window = Main()
        self.other_window.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...