Button to +1 in text box everytime it's clicked (pyqt5)

Hello I have the following code that I want it to start counting from 0 adding 1 every time “pushbutton” is pressed and the value to be shown in “textBrowser”, is this possible as I am having some trouble?:

from PyQt5 import QtCore, QtGui, QtWidgets
 
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(656, 383)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(230, 50, 51, 41))
        self.pushButton.setObjectName("pushButton")
 
self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser.setGeometry(QtCore.QRect(80, 180, 61, 41))
        self.textBrowser.setObjectName("textBrowser")

It should most certainly be possible. What you want is a callback on the pushbutton that increments a counter shown in ythe textbrowser.

It would help if you shared the troubles your having.
Some things tat stand out: Are you sure PyQt supports the method name setObjectName?
Also, the third from last line should be indented as it looks like it should be part of the setupUI method.

I find it always helps to keep a (web) reference to the various PyQt classes at hand.

  1. What’s the line you are having problems with?
  2. What is the error you get, if any?
  3. Check your capitalization of method names and everything else, caps are critical in Python.

You can connect a signal from the pushButton to some function that increments the counter and displays it in the textBrowser. Something like this:

   def inc_counter(self):
        self.counter += 1
        # and add something to display it

   ...
   self.pushButton.clicked.connect(self.inc_counter)

Thanks Benedict, how do I add something to display it?

This code looks like it was generated by Qt Designer. If so, it’s probably not a good idea to edit the generated code, as your changes will be lost when you change the design and re-generate the code.

Instead, I would try either subclassing the generated class as suggested in the Real Python tutorial or generating a .ui file instead and loading that in your program as suggested in the PythonGUIs tutorial.

1 Like