Skip to content

Instantly share code, notes, and snippets.

@oglops
Created February 15, 2016 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oglops/95d412a90797b53c2435 to your computer and use it in GitHub Desktop.
Save oglops/95d412a90797b53c2435 to your computer and use it in GitHub Desktop.
PySide/PyQt truncate text in QLabel based on minimumSize
# http://stackoverflow.com/questions/11446478/pyside-pyqt-truncate-text-in-qlabel-based-on-minimumsize/11764662#11764662
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication,\
QLabel,\
QFontMetrics,\
QPainter
from PyQt4 import QtGui, QtCore
class ElideButton(QtGui.QPushButton):
def __init__(self, parent=None):
super(ElideButton, self).__init__(parent)
font = self.font()
font.setPointSize(9)
self.setFont(font)
def paintEvent(self, event):
painter = QtGui.QStylePainter(self)
metrics = QtGui.QFontMetrics(self.font())
elided = metrics.elidedText(self.text(), Qt.ElideRight, self.width())
option = QtGui.QStyleOptionButton()
self.initStyleOption(option)
option.text = ''
painter.drawControl(QtGui.QStyle.CE_PushButton, option)
painter.drawText(self.rect(), Qt.AlignCenter, elided)
# option.text = elided
# painter.drawControl(QtGui.QStyle.CE_PushButton,option)
if (__name__ == '__main__'):
app = None
if (not QApplication.instance()):
app = QApplication([])
button = ElideButton()
button.setText(
u'This is a really, long and poorly formatted runon sentence used to illustrate a point')
button.setWindowFlags(Qt.Dialog)
button.show()
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment