pyside6qfontmetrics

How to use a specific string to size gui elements in Pyside6?


Because my application may be installed on a bunch of different hardware, I'm looking for a way to insure a QCombobox will be at a specific width, regardless of input font, while avoiding loss of space as much as possible, meaning I don't want to make it wider than I need to.

So I thought I could measure the string I want to use as a measuring stick then use that dimension in my application.

Code

import sys

from PySide6.QtCore import Qt, QObject
from PySide6.QtGui import QFontMetricsF
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow


class MyMainWindow(QMainWindow):
    def __init__(self, app):
        super().__init__()
        pass
         


def main():
    app = QApplication(sys.argv)
     
    app_font= app.font() # returns <PySide6.QtGui.QFont(Segoe UI,9,-1,5,400,0,0,0,0,0,0,0,0,0,0,1) at 0x0000029981F94D40>
    font_metrics = QFontMetricsF(app_font) # returns <PySide6.QtGui.QFontMetricsF object at 0x0000029981FA1BC0>
    # What to do here to get the width of the string "daN/cm²"?
    
    main_window = MyMainWindow(app)
    
    main_window.show()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

Question

How do I get the width of the string I want to use to .setFixedWidth all of the QComboboxes in my application?


Solution

  • To get the size of the text, there's only this bit missing:

    size = font_metrics.size(0, "daN/cm²")
    

    Which will return the size of the bounding box required to print the string to the box. See the documentation about QFontMetrics for the specifics.

    Note that as @musicamante mentionned in the comments, there probably will be more work to do to get the widget the right size to make sure all of the text is properly displayed in all environments.