QListWidget 的一行中的多种字体 [英] multiple fonts in one line of a QListWidget

查看:101
本文介绍了QListWidget 的一行中的多种字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在.ui"文件中的 QListWidget 提出的不同选项中包含文本和希腊符号(用于简单的数学方程)(我过去常常使用 Qt Designer,如果重要的话,我喜欢 python).我希望选项显示如下:

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.)
...

'theta' 和 'phi' 替换为它们的符号.奇怪的是,事实证明这并没有那么简单......

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

如何在 QListWidget 的一行中定义多种字体?Qt Designer 也有同样的问题.

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

推荐答案

一个可能的解决方案是使用 HTML 生成方程的符号,例如以下几行:

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.)

生成以下输出:

θ= φ2(托托等人)
θ= φ2.5(塔塔等人)
θ= 1-log(φ/2)(布朗先生等人)

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

但是 QListWidget 不能识别这种格式,对此的解决方案是创建一个委托来识别这种格式:

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())

输出:

完整示例可在以下链接

这篇关于QListWidget 的一行中的多种字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆