不断闪烁的QPushButton在线程中未正常工作。

huangapple go评论81阅读模式
英文:

continuously Blinking QPushButton not worked right in Thread

问题

我想在程序运行时让QPushButton闪烁,我尝试使用线程来实现,一开始可以工作一段时间,然后就不再闪烁了。以下是我在主窗口初始化结束时编写的代码:

for i in range(len(self.stationMatrix)):
    random.seed(5)
    self.station_threading_blinker.append(threading.Thread(target=self.blinker_station, args=(i,)))
    self.station_threading_blinker[-1].start()
    time.sleep(random.random()+1)

有人能帮助我解决这个问题吗?我怎样才能让我的QPushButton持续闪烁?

英文:

I want to blinking a QPushButton while my program runing , i try to make it with thread , it was working for a few time then it was not binking anymore

`    def blinker_station(self,station):
     while(1):
       #print('station,self.stationblinkervalue[station] : ',station,self.stationblinkervalue[station]) 
       if self.stationblinkervalue[station]==2 :
         self.buttom_stations[station].setStyleSheet("background-color: red")
         
         time.sleep(0.5)
        
         time.sleep(0.5)
       elif self.stationblinkervalue[station]==1:
         self.buttom_stations[station].setStyleSheet("background-color: red")
     
     time.sleep(1)
     
     self.buttom_stations[station].setStyleSheet("background-color: white")
     
     time.sleep(0.5)
    
     time.sleep(0.5)
   elif self.stationblinkervalue[station]==0:
     self.buttom_stations[station].setStyleSheet("background-color: white")
     
     time.sleep(0.5)
     
     time.sleep(0.5)`

that is , what i wrote at the end of my MainWindows init :

for i in range(len(self.stationMatrix)):
          random.seed(5)
         
          self.station_threading_blinker.append(threading.Thread(target=self.blinker_station, args=(i,)))
          self.station_threading_blinker[-1].start()
          time.sleep(random.random()+1)

can someone help me in this problem , how can i let my QPushButton continuously Blinking

答案1

得分: 2

I can provide the translation of the code portion you shared:

我不确定切换样式表以更改背景颜色是否是使按钮闪烁的最有效方式但使用 [QTimer][1] 是进行定时操作的方法

您可以在计时器上设置一个较短的间隔例如500毫秒),并将其超时信号连接到一个方法以切换按钮的背景颜色

```python
import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QHBoxLayout
from PyQt5.QtCore import QTimer


class Window(QWidget):
    def __init__(self):
        super().__init__()
        layout = QHBoxLayout(self)
        self.blinker = QPushButton("我在闪烁")
        layout.addWidget(self.blinker)

        self.background_colour = 'red'

        self.blink_timer = QTimer()
        self.blink_timer.setInterval(500)
        self.blink_timer.timeout.connect(self.switch_background_colour)
        self.blink_timer.start()

    def switch_background_colour(self):
        if self.background_colour == 'red':
            self.background_colour = 'white'
        elif self.background_colour == 'white':
            self.background_colour = 'red'

        self.blinker.setStyleSheet(f"background-color: {self.background_colour}")


if __name__ == "__main__":
    app = QApplication([])
    window = Window()
    window.show()
    sys.exit(app.exec())

Please note that I have provided the translated code portion only, as per your request.

<details>
<summary>英文:</summary>

I&#39;m not sure if switching stylesheet to change the background colour is the most efficient way to make a button blink, but a [QTimer][1] is the way to go to do the timing.

You set a short interval on a timer (like 500 msec) and connect its timeout signal to a method to switch the background colour on the button.

    import sys
    from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QHBoxLayout
    from PyQt5.QtCore import QTimer
    
    
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            layout = QHBoxLayout(self)
            self.blinker = QPushButton(&quot;I&#39;m blinking&quot;)
            layout.addWidget(self.blinker)
    
            self.background_colour = &#39;red&#39;
    
            self.blink_timer = QTimer()
            self.blink_timer.setInterval(500)
            self.blink_timer.timeout.connect(self.switch_background_colour)
            self.blink_timer.start()
    
        def switch_background_colour(self):
            if self.background_colour == &#39;red&#39;:
                self.background_colour = &#39;white&#39;
            elif self.background_colour == &#39;white&#39;:
                self.background_colour = &#39;red&#39;
    
            self.blinker.setStyleSheet(f&quot;background-color: {self.background_colour}&quot;)
    
    
    if __name__ == &quot;__main__&quot;:
        app = QApplication([])
        window = Window()
        window.show()
        sys.exit(app.exec())


  [1]: https://doc.qt.io/qt-6/qtimer.html

</details>



# 答案2
**得分**: 0

I have a solution now!

以下是您提供的代码的翻译:

我现在有一个解决方案!

这是我在MainWindows Init中编写的部分:

for self.i in range(len(self.stationMatrix)):
self.worker_thread.append(WorkerThread())
self.worker_thread[self.i].gui_text = self.i
self.worker_thread[self.i].blinker_mode = 0
self.worker_thread[self.i].job_done.connect(self.on_job_done)
self.worker_thread[self.i].start()
time.sleep(0.5)

初始化结束

#########################################################################################################
def on_job_done(self, t):
# print("Generated string: ", t)
# self.buttom_stations[t1].setStyleSheet(t[0])
matrix = t.split('/')
self.buttom_stations[int(matrix1)].setStyleSheet(matrix[0])

这是另一个执行工作的WorkerThread类:

class WorkerThread(QtCore.QThread):
job_done = QtCore.pyqtSignal('QString')

def __init__(self, parent=None):
    super(WorkerThread, self).__init__(parent)
    self.gui_text = None
    self.blinker_mode = None
    self.x = "background-color: white"

def do_work(self):
    t = ' '
    while True:
        # print(self.gui_text)
        if self.blinker_mode == 1:
            if self.x == "background-color: red":
                t = "background-color: white" + '/' + str(self.gui_text)
                self.job_done.emit(t)
                self.x = "background-color: white"
                time.sleep(0.5)
            if self.x == "background-color: white":
                t = "background-color: red" + '/' + str(self.gui_text)
                self.job_done.emit(t)
                self.x = "background-color: red"
                time.sleep(0.5)
        if self.blinker_mode == 0:
            # if self.x == "background-color: white":
            t = "background-color: white" + '/' + str(self.gui_text)
            self.job_done.emit(t)
            self.x = "background-color: white"
            time.sleep(1)
        if self.blinker_mode == 2:
            # if self.x == "background-color: red":
            t = "background-color: red" + '/' + str(self.gui_text)
            self.job_done.emit(t)
            self.x = "background-color: red"
            time.sleep(1)

def run(self):
    self.do_work()

现在,如果您想更改闪烁模式,只需调用:

self.worker_thread[index_of_worker].blinker_mode = Mode_of_blinker


请注意,代码中的注释和特殊字符可能需要进一步处理,以适应您的编程环境。

<details>
<summary>英文:</summary>

i have a solution Now ! 

that what i write i th MainWindows Init :


            for self.i in range(len(self.stationMatrix)):
                      self.worker_thread.append(WorkerThread())
                      self.worker_thread[self.i].gui_text = self.i
                      self.worker_thread[self.i].blinker_mode = 0
                      self.worker_thread[self.i].job_done.connect(self.on_job_done)
                      self.worker_thread[self.i].start()
                      time.sleep(0.5)
         #End of INIT             
    #########################################################################################################
        def on_job_done(self, t):
            #print(&quot;Generated string : &quot;, t)
            # self.buttom_stations[t[1]].setStyleSheet(t[0])
            matrix=t.split(&#39;/&#39;)
            self.buttom_stations[int(matrix[1])].setStyleSheet(matrix[0])

that is the other class WorkerThread which make the work :

    class WorkerThread(QtCore.QThread):
        job_done = QtCore.pyqtSignal(&#39;QString&#39;)
        def __init__(self, parent=None):
            super(WorkerThread, self).__init__(parent)
            self.gui_text = None
            self.blinker_mode = None
            self.x=&quot;background-color: white&quot;
        def do_work(self):
            
            t=&#39; &#39;
            while(1):
             #   print(self.gui_text)
                if self.blinker_mode==1:
                 if self.x ==&quot;background-color: red&quot; : 
                     t=&quot;background-color: white&quot;+&#39;/&#39;+str(self.gui_text)
                     self.job_done.emit(t)
                     self.x=&quot;background-color: white&quot;
                     time.sleep(0.5)
                 if self.x ==&quot;background-color: white&quot; :
                  t=&quot;background-color: red&quot;+&#39;/&#39;+str(self.gui_text)
                  self.job_done.emit(t)
                  self.x=&quot;background-color: red&quot;
                  time.sleep(0.5)
                if self.blinker_mode==0:
                #   if self.x ==&quot;background-color: white&quot; : 
                     t=&quot;background-color: white&quot;+&#39;/&#39;+str(self.gui_text)
                     self.job_done.emit(t)
                     self.x=&quot;background-color: white&quot;
                     time.sleep(1)
                if self.blinker_mode==2:
                #   if self.x ==&quot;background-color: red&quot; : 
                     t=&quot;background-color: red&quot;+&#39;/&#39;+str(self.gui_text)
                     self.job_done.emit(t)
                     self.x=&quot;background-color: red&quot;
                     time.sleep(1)
                 
                
        def run(self):
            self.do_work()


and now if i want to change the blinking i just need to call :

self.worker_thread[index_of_worker].blinker_mode = Mode_of_blinker

</details>



huangapple
  • 本文由 发表于 2023年4月17日 14:10:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定