Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6993995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T19:50:07+00:00 2026-05-27T19:50:07+00:00

I have a QLabel of a fixed width. I need to check (periodically) that

  • 0

I have a QLabel of a fixed width.
I need to check (periodically) that the entire string fits inside the QLabel at its current width, so I can resize it appropriately.

To do this, I need to obtain the ‘pixel length’ of the string.
(The total amount of horizontal pixels required to display the string).
It should be noted that the point size of the QLabel never changes.

Example of 'Pixel Width' of a string

I can not simply check the amount of characters present, since some characters are subscript / superscript and contribute differently to the width of the entire string.
(This is to say there is no simple relationship between pixel width and the amount of characters)

Is there any abstracted, super conveniant function for this?

Specs:
Python 2.7.1
PyQt4
Windows 7

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T19:50:08+00:00Added an answer on May 27, 2026 at 7:50 pm

    To get the precise pixel-width of the text, you must use QFontMetrics.boundingRect.

    Do not use QFontMetrics.width, because it takes into account the left and right bearing of the characters. This will often (but not always) lead to results which can be several pixels more or less than the full pixel-width.

    So, to calculate the pixel-width of the label text, use something like:

    width = label.fontMetrics().boundingRect(label.text()).width()
    

    EDIT

    There are three different QFontMetrics methods which can be used to calculate the “width” of a string: size(), width() and boundingRect().

    However, although they all give slightly different results, none of them seems to consistently return the exact pixel-width in all circumstances. Which one is best depends mostly on the current font-family in use and on which particular characters are at the beginning and end of the string.

    I have added below a script that tests the three methods. For me, the boundingRect method gives the most consistent results. The other two methods tend to be either slightly too wide, or clip the second text sample when a serif font is used (this is with PyQt 4.9 and Qt 4.8 on Linux).

    from PyQt4 import QtGui, QtCore
    
    class Window(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)
            self.setAutoFillBackground(True)
            self.setBackgroundRole(QtGui.QPalette.Mid)
            self.setLayout(QtGui.QFormLayout(self))
            self.fonts = QtGui.QFontComboBox(self)
            self.fonts.currentFontChanged.connect(self.handleFontChanged)
            self.layout().addRow('font:', self.fonts)
            for text in (
                u'H\u2082SO\u2084 + Be',
                u'jib leaf jib leaf',
                ):
                for label in ('boundingRect', 'width', 'size'):
                    field = QtGui.QLabel(text, self)
                    field.setStyleSheet('background-color: yellow')
                    field.setAlignment(QtCore.Qt.AlignCenter)
                    self.layout().addRow(label, field)
            self.handleFontChanged(self.font())
    
        def handleFontChanged(self, font):
            layout = self.layout()
            font.setPointSize(20)
            metrics = QtGui.QFontMetrics(font)
            for index in range(1, layout.rowCount()):
                field = layout.itemAt(index, QtGui.QFormLayout.FieldRole).widget()
                label = layout.itemAt(index, QtGui.QFormLayout.LabelRole).widget()
                method = label.text().split(' ')[0]
                text = field.text()
                if method == 'width':
                    width = metrics.width(text)
                elif method == 'size':
                    width = metrics.size(field.alignment(), text).width()
                else:
                    width = metrics.boundingRect(text).width()
                field.setFixedWidth(width)
                field.setFont(font)
                label.setText('%s (%d):' % (method, width))
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(app.exec_())
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am building a small GUI interface and I have a QLabel that draws
I have a MainWindow. On MainWindow I have multiple Qlabel's. Now, i need to
I have a simple item delegate of QStyledItemDelegate type and inside its paint method
I have a QLabel without any text but with a QPixmap image. I can
I have a QLabel with a Qt stylesheet that sets a dark background: QLabel
I have a main PyQt window, from which I need to get a string
I need to display several international scripts within a same string in a QLabel.
I have a QLabel and a QLineEdit inside a QWidget. When I have the
I have a QLabel that I'm constantly setting it's pixmap (video playback). In my
I have a QLabel that is loaded with a pixmap. I have it set

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.