微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Qt displayAlignment 没有右对齐

如何解决Qt displayAlignment 没有右对齐

我正在使用 PyQt 编写应用程序。我将 QListView 与 qstyledItemDelegate 一起使用,我需要在左侧对齐一些项目,在右侧对齐一些项目。认情况下,它们都在左侧对齐。但是,我仍然不知道如何在右侧对齐它们。我发现这个问题 How I can align values exported from database with query in PyQt5 table view 看起来像我需要的东西,但 displayAlignment 似乎没有改变任何东西。这是我的代码

import sys

from PyQt5.QtCore import (
    QAbstractListModel,QMargins,Qt,QSize,)
from PyQt5.QtGui import (
    QPainter,QFont,QFontMetrics,)
from PyQt5.QtWidgets import (
    QApplication,QListView,QMainWindow,QVBoxLayout,QWidget,qstyledItemDelegate,)

BUBBLE_PADDING = QMargins(15,5,15,5)
TEXT_PADDING = QMargins(25,25,15)
FONT_SIZE = 14
FONT_STYLE = "Times"
font = 0

class MessageDelegate(qstyledItemDelegate):
    def initStyleOption(self,option,index):
        super(MessageDelegate,self).initStyleOption(option,index)
        option.displayAlignment = Qt.AlignRight

    def paint(self,painter,index):
        global font
        text = index.model().data(index,Qt.displayRole)
        option.rect.setSize(self.sizeHint(option,index))
        option.displayAlignment = Qt.AlignRight
        print(int(option.displayAlignment))
        bubblerect = option.rect.marginsRemoved(BUBBLE_PADDING)
        textrect = option.rect.marginsRemoved(TEXT_PADDING)
        painter.setPen(Qt.cyan)
        painter.setBrush(Qt.cyan)
        painter.drawRoundedRect(bubblerect,10,10)
        painter.setPen(Qt.black)
        painter.setFont(font)
        painter.drawText(textrect,Qt.TextWordWrap,text)

    def sizeHint(self,Qt.displayRole)
        metrics = QFontMetrics(font)
        rect = option.rect.marginsRemoved(TEXT_PADDING)
        rect = metrics.boundingRect(rect,text)
        rect = rect.marginsAdded(TEXT_PADDING)
        return rect.size()


class MessageModel(QAbstractListModel):
    def __init__(self,*args,**kwargs):
        super(MessageModel,self).__init__(*args,**kwargs)
        self.messages = []

    def data(self,index,role):
        if role == Qt.displayRole:
            return self.messages[index.row()]

    def rowCount(self,index):
        return len(self.messages)

    def add_message(self,text):
        if text:
            self.messages.append((text))
            self.layoutChanged.emit()


class MainWindow(QMainWindow):
    def __init__(self):
        global font
        super(MainWindow,self).__init__()
        font = QFont(FONT_STYLE,FONT_SIZE)
        self.resize(int(QApplication.primaryScreen().size().width() * 0.3),int(QApplication.primaryScreen().size().height() * 0.5))
        main_layout = QVBoxLayout()
        self.messages = QListView()
        self.messages.setItemDelegate(MessageDelegate())
        self.model = MessageModel()
        self.messages.setModel(self.model)
        self.model.add_message("Hello,world!")
        main_layout.addWidget(self.messages)
        self.w = QWidget()
        self.w.setLayout(main_layout)
        self.setCentralWidget(self.w)


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

And here is the result. 如您所见,尽管绘制函数中打印的值是 2 (Qt.AlignRight),但消息仍然在左侧对齐。 (我已经分配了 Qt.AlignRight 2 次,因为函数 initStyleOption 从未被调用过)

解决方法

设置样式选项的值只有在使用时才有意义,例如在调用 QStyle 函数时。

您通过自己绘制所有内容来覆盖 paint,因此样式选项的任何更改都毫无用处。
相反,您应该不要更改除 option.rect 之外的任何函数中的选项(尤其是 initStyleOption),而是基于以下内容创建选项(或其对象)的新实例取而代之的是作为参数接收的那个。

由于要将矩形向右对齐,因此需要根据选项 rect 的右侧 减去 所需宽度,使用其 X 坐标构造一个新矩形。

    def paint(self,painter,option,index):
        text = index.model().data(index,Qt.DisplayRole)
        size = self.sizeHint(option,index)
        rect = QRect(
            option.rect.right() - size.width(),option.rect.y(),size.width(),size.height())
        bubblerect = rect.marginsRemoved(BUBBLE_PADDING)
        textrect = rect.marginsRemoved(TEXT_PADDING)
        painter.setPen(Qt.cyan)
        painter.setBrush(Qt.cyan)
        painter.drawRoundedRect(bubblerect,10,10)
        painter.setPen(Qt.black)
        painter.setFont(font)
        painter.drawText(textrect,Qt.TextWordWrap,text)

只要有可能,就应该始终避免使用全局变量(如果您不知道如何使用它们,请不要使用它们,也就是:如果您知道如何使用它们,您就不会使用它们)。如果要为委托设置字体,请使用首选字体为其 __init__ 添加参数,并将其设置为实例属性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。