我想拥有一个带4个按钮的简单GUI。如果只是单击按钮,则应执行功能A,对于短按钮按下(例如1秒),应执行功能B,最后应执行长按(例如> 2s)功能C. 想象一下柜台。 如果单击该按钮,它将重置为0 如果您短按按钮,计数器将增加1,例如t = 1秒 如果长按按钮,计数器将增加10,直到释放按钮。
有人有想法吗?我试图通过第二个线程来完成它,但是我没有找到像你可以启动它一样停止线程的可能性
答案 0 :(得分:6)
如果您使用继承QAbstractButton的小部件,这在PyQt中很容易实现。不需要任何计时器或单独的线程。只需使用内置的auto-repeat功能,并记录当前状态。
这是一个简单的演示:
from PyQt4 import QtGui, QtCore
class Button(QtGui.QPushButton):
def __init__(self, *args, **kwargs):
QtGui.QPushButton.__init__(self, *args, **kwargs)
self.setAutoRepeat(True)
self.setAutoRepeatDelay(1000)
self.setAutoRepeatInterval(1000)
self.clicked.connect(self.handleClicked)
self._state = 0
def handleClicked(self):
if self.isDown():
if self._state == 0:
self._state = 1
self.setAutoRepeatInterval(50)
print 'press'
else:
print 'repeat'
elif self._state == 1:
self._state = 0
self.setAutoRepeatInterval(1000)
print 'release'
else:
print 'click'
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
button = Button('Test Button')
button.show()
sys.exit(app.exec_())
答案 1 :(得分:2)
start_time = None
def onLeftDown(e):
global running
running = True
ct =0
while running:
ct += 1
do_something(ct)
def onLeftUp(e):
print "You Pressed For %s Seconds!"%(time.time()-start_time)
my_btn = wx.Button(parent,-1,"Click Me!")
my_btn.Bind(wx.EVT_LEFT_DOWN,onLeftDown)
my_btn.Bind(wx.EVT_LEFT_UP,onLeftUp)
我对QT不是很熟悉,但也许你可以修改这个wx代码来做你想要的......
import wx
ct = 0
def counting():
global running
global ct
if running:
ct +=1
print ct
wx.CallLater(1,counting)
else:
print "OK DONE COUNTING AT:",ct
def onLeftDown(evt):
global running
running = True
counting()
def onLeftUp(evt):
print "STOP NOW!!"
global running
running = False
a = wx.App(redirect=False)
f = wx.Frame(None,-1,"asdasd")
b = wx.Button(f,-1,"Click Me")
b.Bind(wx.EVT_LEFT_DOWN,onLeftDown)
b.Bind(wx.EVT_LEFT_UP,onLeftUp)
f.Show()
a.MainLoop()