multiple fonts in one line of a QListWidget

可紊 提交于 2020-01-24 21:54:46

问题


I need to include text and greek symbols (for simple mathematical equations) in the different options proposed by a QListWidget in a '.ui' file (I use to work with Qt Designer and I like python if it matters). I want the options to appear like this:

theta = phi^2 (toto et al.)
theta = phi^2.5 (tata et al.)
theta = 1-log(phi/2) (mister brown et al.)
...

with 'theta' and 'phi' replaced by their symbol. Strangely, this turns out to be not so simple...

How to define several fonts in one line of a QListWidget ? Same question with Qt Designer.


回答1:


A possible solution is to use HTML to generate the symbols of the equation, for example the following lines:

&theta;  = &phi;<sup>2</sup> (toto et al.)
&theta;  = &phi;<sup>2.5</sup> (tata et al.)
&theta;  = 1-log(&phi;/2) (mister brown et al.)

generate the following output:

θ = φ2 (toto et al.)
θ = φ2.5 (tata et al.)
θ = 1-log(φ/2) (mister brown et al.)

but QListWidget does not recognize this format, a solution for this is to create a delegate to recognize that format:

class HTMLDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter, option, index):
        self.initStyleOption(option,index)
        painter.save()
        doc = QtGui.QTextDocument()
        doc.setHtml(option.text)
        option.text = ""
        option.widget.style().drawControl(QtWidgets.QStyle.CE_ItemViewItem, option, painter)

        painter.translate(option.rect.left(), option.rect.top())
        clip = QtCore.QRectF(0, 0, option.rect.width(), option.rect.height())
        doc.drawContents(painter, clip)
        painter.restore()

    def sizeHint(self, option, index):
        self.initStyleOption(option,index)
        doc = QtGui.QTextDocument()
        doc.setHtml(option.text)
        doc.setTextWidth(option.rect.width())
        return QtCore.QSize(doc.idealWidth(), doc.size().height())

then we add him as a delegate with the following lines:

qlistwidget.setItemDelegate(HTMLDelegate())

Output:

The complete example can be found in the following link



来源:https://stackoverflow.com/questions/47890913/multiple-fonts-in-one-line-of-a-qlistwidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!