سؤال

I'm programming a simple GUI with QtGUI in Python that allows users to start a routine by clicking a button (button1) and after 10 seconds there should be the option to click another button (button2) to start some routine. I tried following:

self.button1=QtGui.QPushButton('Button1',self)
self.button1.clicked.connect(self.button1clicked)

self.button2=QtGui.QPushButton('Button2',self)
self.button2.setEnabled(False)
self.button2.clicked.connect(self.button2clicked)

def button1clicked(self):
    self.button2.setEnabled(False)
    self.button2.clicked.disconnect()
    self.timeNow = time.time()
    self.enablebutton2()

def enablebutton2(self):
    while(True):
        if time.time() - self.timeNow > 10:
            self.button2.clicked.connect(self.button2clicked)
            self.button2.setEnabled(True)
            break

def button2clicked(self):
    someroutine()

It seems to work, the button is disabled at the beginning and when I click it nothing happens but then after I clicked button1 and the 10 seconds are over button2 receives all the clicks I did before.

This should not happen, how can I make sure that all those clicks are discarded when button2 is disabled?

هل كانت مفيدة؟

المحلول

You no need to do self.button2.clicked.disconnect() as you are disabling button2. That itself is sufficient. Secondly in you are calling enableButton2() from slot of button1 this is wrong. You are blocking main thread for 10 seconds in your while loop. This is wrong way of doing things.

Instead you should use a QTimer set time for 10 seconds and start it from button1's slot. In timer's slot you can enable button2. see QTimer here, Following is C++ example you can convert it in python easily

 QTimer *timer = new QTimer(this);
 connect(timer, SIGNAL(timeout()), this, SLOT(update()));
 timer->start(1000);

نصائح أخرى

You are also connecting button2 twice ... Once when you create the button and again in enablebutton2. Only the second connect should be used. That way even the disconnect statement is not required.

Also as stated by @Abhishek you need to use QTimer as you are blocking the UI for 10 seconds. C++ code would look somewhat like this

QPushButton *button1 = new QPushButton("Button1");
connect(button1, SIGNAL(clicked()), this, SLOT(button1clicked()));

QPushButton *button2 = new QPushButton("Button1");
button2->setEnabled(false);

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(enableButton2()));  

button1clicked()
{
    timer->start();
}

enableButton2()
{
    button2->setEnabled(true);
    connect(button2, SIGNAL(clicked()), this, SLOT(button2clicked()));
}

button2clicked()
{
    someroutine();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top