import sys
import time
from PySide2 import QtCore, QtWidgets


class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle(QtCore.qVersion())
        self.button1 = QtWidgets.QPushButton("isrun=false")
        self.button2 = QtWidgets.QPushButton("mythread.terminate")
        self.button3 = QtWidgets.QPushButton("Start")
        self.button4 = QtWidgets.QPushButton("Close")
        self.layout = QtWidgets.QHBoxLayout(self)
        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.layout.addWidget(self.button3)
        self.layout.addWidget(self.button4)
        self.layout.addStretch()

        self.button1.clicked.connect(self.setF)
        self.button2.clicked.connect(self.termThread)
        self.button3.clicked.connect(self.startThread)
        self.button4.clicked.connect(self.close)

        self.mythread = AThread(self)

    def setF(self):
        self.mythread._is_running = False
        print("isrun = False")

    def termThread(self):
        self.mythread.terminate()
        print("thread stopped")

    def startThread(self):
        if self.mythread.Start():
            print("thread started")
        else:
            print("thread still running?")


class AThread(QtCore.QThread):

    def __init__(self, parent):
        super().__init__(parent)

    def Start(self):
        if not self.isRunning():
            self._is_running = True
            self.start()
            return True
        return False

    def run(self):
        while self._is_running:
            print("thread ping")
            time.sleep(1)
        print("thread terminating")


if __name__ == "__main__":
    print('Python {}.{}'.format(sys.version_info[0], sys.version_info[1]))
    print(QtCore.QLibraryInfo.build())
    app = QtWidgets.QApplication([])
    widget = MyWidget()
    widget.show()
    widget.startThread()

    sys.exit(app.exec_())
