Peter Greaves
Peter Greaves

Reputation: 327

Deactivate all buttons during execution - PyQt

I'm building a GUI with PyQt, and I'd like to make it possible to stop all the buttons doing anything while code is running. Lets say the user is copying a lot of data from a table - it would be easy for them to click another button while it is happening even if the cursor has changed to the egg timer. Any ideas or workarounds for this without going through all buttons and greying them out one by one? I'd be happy with a workaround too!

Thanks for any ideas,

Pete

Upvotes: 0

Views: 3464

Answers (1)

Vincent
Vincent

Reputation: 13415

You could use a modal QDialog. From the QDialog pyqt documentation:

A modal dialog is a dialog that blocks input 
to other visible windows in the same application.

Also, QProgressDialog is a very convenient tool to handle blocking action in a very simple way. Here is an example :

from PyQt4 import QtGui, QtCore
from time import sleep

class Test(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Test, self).__init__(parent)
        button = QtGui.QPushButton("Button")
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(button)
        self.setLayout(hbox)
        button.clicked.connect(self.slot)

    def slot(self):
        progress = QtGui.QProgressDialog(self)
        progress.setWindowModality(QtCore.Qt.WindowModal)
        progress.setLabel(QtGui.QLabel("Doing things..."))
        progress.setAutoClose(True)
        for i in range(101):
             progress.setValue(i);
             sleep(0.05)
             if progress.wasCanceled():
                 break

if __name__=="__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    myapp = Test()
    myapp.show()
    sys.exit(app.exec_())

Upvotes: 3

Related Questions