QLabel setText() cannot handle change of text length
-
I am calling setText() to change the text of a Qlabel when a user presses a button. The text is just an integer that is incremented by one. Everything goes fine until 9 than it goes to 1 as it cannot show the 0 of the 10. What code should I add?
def update_amount_of_faces(self): self.label3.setText(str(len(self.a_list))) #List has length of 10 text shown is 1
-
@FreeMake okay since you did not give a simple example program to test your function here is one and using Python 3.7 / PyQt5 on Win10 this works perfectly fine. I would suggest checking the values you think you ought to be getting to make sure they are what you are getting. Also QLabel does not have an easy way (that I could see) of restricting the length other than somehow making the label container so small that it will only show the first value in which case perhaps check the contents of your Label after modification to see what it actually contains. If it contains '10' when only showing '1' this means somehow your display area is really small.
from sys import exit as sysExit from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class CenterPane(QWidget): def __init__(self): QWidget.__init__(self) self.MyButtn = QPushButton('Update', self) self.MyButtn.clicked.connect(self.on_click) self.MyTList = QLineEdit('A, B, C, D, E', self) # Simply type the following into the Text Box: , F, G, H, I, J # press the Update button self.label3 = QLabel('0', self) vbox = QVBoxLayout(self) vbox.addWidget(self.MyButtn) vbox.addWidget(self.MyTList) vbox.addWidget(self.label3) self.setLayout(vbox) @pyqtSlot() def on_click(self): Value = self.MyTList.text() self.a_list = Value.split(',') print("List:",self.a_list) print("Count:",len(self.a_list)) self.update_amount_of_faces() def update_amount_of_faces(self): self.label3.setText(str(len(self.a_list))) #List has length of 10 text shown is 1 class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) Left = 200 Top = 200 Width = 250 Height = 100 self.setWindowTitle('Main Window') self.setGeometry(Left, Top, Width, Height) self.setCentralWidget(CenterPane()) if __name__ == "__main__": mainApp = QApplication([]) mainGUI = MainWindow() mainGUI.show() sysExit(mainApp.exec_())
-
This is a sizeHint/layout problem. You are not allowing your widget to have enough space to display more than a single digit. Set your minimum size hint a bit larger and try it again.
-
@Kent-Dorfman I am not sure how you can make that claim without making a major assumption as to what @FreeMake did as they did not denote having changed their layout and/or even used sizeHint both of which would be relatively significant changes as opposed to the simple usage which is what was presented. Not saying your claim is incorrect because it is the only thing I can think of as well but it was not mentioned thus I cannot safely make that assumption and that is why I presented some code to show it working properly so that @FreeMake could try and discern where there problem resides.
-
I make that assertion because that is the only thing it could be...simply writing text to a label is a no-brainer. If it is truncating the text then the layout information and/or widget geometry rules are at fault...assuming self.a_list has the value that he thinks it does
-
@Kent-Dorfman right "assuming that the data is correct" which btw we cannot assume at this point as that has not been ascertained.
Further if one considers that changing a layout and/or using sizeHint are not what most folks asking this kind of question would generally do your assumption falls even shorter.
Now this is not to say (as I stated) that your assumption is incorrect all I am saying is that it is not a good assumption and your off handed answer could actually lead to more confusion as the individual may not even know what those are or how they work. Basically meet the individual where they seem to be at, not where you are and try to ascertain exactly what you can and cannot from the question as stated -- do not read into it. If you need the question clarified ask for that because making logical leaps can as I stated lead to more confusion and that is not what I am thinking you are trying to do. I hope that clarifies what I mean.
-
@Denni said in QLabel setText() cannot handle change of text length:
Further if one considers that changing a layout and/or using sizeHint are not what most folks asking this kind of question would generally do your assumption falls even shorter.
whatevah!
-
Hi all, apologies, I was really tired at the moment of writing and should have added a minimal example. I checked the length of my list and it is really 10. @Denni I cannot run your example as I am using the python version that came with FreeCAD which does not have the PyQt5 implemented.
The window that I have seems to have a lot of space for an extra digit, where should I put the size hint?
However here is a minimal example, you can click add faces to see the counter increment:
from PySide import QtGui, QtCore # UI Class definitions class SelectFastenerFaces(QtGui.QDialog): """""" def __init__(self): super(SelectFastenerFaces, self).__init__() self.initUI() def initUI(self): self.selected_faces = [] self.result = "Cancelled" # create our window # define window xLoc,yLoc,xDim,yDim self.setGeometry(150, 150, 400, 350) self.setWindowTitle("Select fastener geometry of visible object") self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) # create some Labels self.label1 = QtGui.QLabel("Select the fastener faces", self) self.label1.setFont('Courier') # set to a non-proportional font self.label1.move(0, 0) self.label2 = QtGui.QLabel("Number of selected faces: ", self) self.label2.setFont('Courier') # set to a non-proportional font self.label2.move(0, 20) self.label3 = QtGui.QLabel("0", self) self.label3.setFont('Courier') # set to a non-proportional font self.label3.move(200, 20) # add faces button addfacesButton = QtGui.QPushButton('Add Faces', self) addfacesButton.clicked.connect(self.onaddfaces) addfacesButton.setAutoDefault(True) addfacesButton.move(260, 140) # clear selection button clearButton = QtGui.QPushButton('Clear', self) clearButton.clicked.connect(self.onClear) clearButton.setAutoDefault(True) clearButton.move(150, 140) # cancel button cancelButton = QtGui.QPushButton('Cancel', self) cancelButton.clicked.connect(self.onCancel) cancelButton.setAutoDefault(True) cancelButton.move(150, 280) # OK button okButton = QtGui.QPushButton('OK', self) okButton.clicked.connect(self.onOk) okButton.move(260, 280) # now make the window visible self.show() def onaddfaces(self): self.selected_faces.append("face") # Update the faces self.update_amount_of_faces() def update_amount_of_faces(self): print(str(len(self.selected_faces))) self.label3.setText(str(len(self.selected_faces))) def onClear(self): self.selected_faces = [] self.update_amount_of_faces() def onCancel(self): self.result = "Cancelled" self.close() def onOk(self): self.result = "OK" self.close() # Class definitions # Function definitions # code *********************************************************************************** def main(): """Asks the users to select faces from an object 'obj', returns the selected faces in a list.""" # Constant definitions userCancelled = "Cancelled" userOK = "OK" form = SelectFastenerFaces() form.exec_() if form.result == userCancelled: return None # steps to handle user clicking Cancel if form.result == userOK: # steps to handle user clicking OK return form.selected_faces if __name__ == '__main__': main()
-
Okay @FreeMake first pyside means your still using Qt4 which was deprecated in 2015 further pyside is no longer supported as well since it uses python 2.7 (or there abouts which is being deprecated next year). Now you can get both pyside2 (which is not needed as pyqt5 is directly supported within the latest version of python upon doing a pip install of pyqt5) and the latest version of python 3.7 for free so I would suggest uninstalling that old stuff and upgrading to the current stuff. That being said I copied your code and after tweaking it a little got it to run in python 3.7 pyqt5 and reproduced your issue (and its not due to changing a layout and/or using sizeHint).
Your issue resides in line 32 (or close to that) where you declare:
self.label3 = QLabel("0", self)
The "0" is being used as a Mask I extended it to "00" and could then see 2 digit numbers but it did not show 3 digit numbers. My suggestion is to use 2 labels side by side. The first label holding the text you want and the second label holding nothing or "0" initially -- BUT then -- fully re-populate with the new value you want to show each time. Or figure out how to use that QLabel so it does what you are wanting it to do.
Note the former solution is what I have used in other languages because there is really no need to continue adding text to the end of an exiting static label for it is a lot simpler (and easier for the computer) to completely overwrite a 2nd label that is used only for that purpose.
P.S. In all future questions be sure to add the version of the languages you are using as well as the OS for instance I am using python 3.7 pyqt5 on Win10 this helps to inform anyone attempting to help you to compare pears to pears because you rarely get the proper results by comparing pears with avocados even if avocados are sometimes referred to as alligator pears