0

I started a thread to call a method continuously to switch the window, but it seems that the window will jam,This is the class I override

class N1(QMainWindow,s1.Ui_MainWindow):
    def __init__(self):
        super(N1, self).__init__()
        self.resize(800,600)
        self.setWindowTitle('screen2')

class N2(QMainWindow,s2.Ui_MainWindow):
    def __init__(self):
        super(N2, self).__init__()
        self.resize(800,600)
        self.setWindowTitle('screen1')
        self.show()
    def change_screen(self):
        self.N1 = N1()
        self.N1.show()
        self.hide()
    def trans_screen(self):
        self.N1.hide()
        self.show()

This is the thread I started:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = N2()
    t1 = threading.Thread(target=change,args=(window,))
    t1.start()
    sys.exit(app.exec_())

This is how I keep switching windows

def change(window):
    WIN = window
    while True:
        print(1)
        time.sleep(5)
        WIN.change_screen()
        time.sleep(5)
        WIN.trans_screen()
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • I don't know what you mean by "jam", but you should *never* try to do anything like that: access to UI objects is not allowed from external threads. If you need to call a function that does anything related to the UI after a certain amount of time, use [QTimer](https://doc.qt.io/qt-5/qtimer.html). I suggest you to do some research as there are literally hundreds of posts about these topics, including achieving what you're trying to do. – musicamante Jun 16 '21 at 10:28
  • Also, please be more careful when providing code, always check the output in the post preview, and check the guidelines about [formatting code](https://meta.stackoverflow.com/a/251362) (I already fixed your post, but keep this in mind for future reference). – musicamante Jun 16 '21 at 10:32

1 Answers1

0

Qt does not support controlling widgets (calling methods on them) from threads different than the main thread.

You need to implement the logic within the Qt main loop in your main thread. For example, use a QTimer in the main thread and go from event to event instead of the sleep calls you have in your auxiliary thread.

You can also use Qt signals/slots to communicate/trigger from other threads into the main thread.

ypnos
  • 50,202
  • 14
  • 95
  • 141