无法在 Pyqt5 中更改 qtextedit 的背景边框,有啥建议吗?

Posted

技术标签:

【中文标题】无法在 Pyqt5 中更改 qtextedit 的背景边框,有啥建议吗?【英文标题】:can't change backgrund border of qtextedit in Pyqt5, any suggestions?无法在 Pyqt5 中更改 qtextedit 的背景边框,有什么建议吗? 【发布时间】:2021-01-11 21:26:07 【问题描述】:

我无法更改文本的背景形状。有可能还是我应该尝试另一种方法来解决它。谢谢。这是我到目前为止所拥有的。我尝试在 qtextedit 中将 broder-radius 添加到 html,但每当我尝试时,QtCreator 不接受我所做的并将代码重置为我现在共享的当前 html。

font = QtGui.QFont()
font.setFamily("MS Shell Dlg 2")
font.setPointSize(8)
font.setStrikeOut(False)
self.ui.textEdit.setTextBackgroundColor(QtGui.QColor(143,188,143))
self.ui.textEdit.setAlignment(QtCore.Qt.AlignRight)
self.ui.textEdit.append("Here is the background i want to change. Iwant it to be round instead of a corner.")
self.ui.textEdit.setLineWrapMode(self.ui.textEdit_2.LineWrapMode(3))        
self.ui.textEdit.setLineWrapColumnOrWidth(40)
self.ui.textEdit.setWordWrapMode(1)
self.ui.textEdit.append("")
self.ui.textEdit.setFont(font)



self.textEdit_2.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li  white-space: pre-wrap; \n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Mit der Nutzung Des Chatbots stimmen Sie der Nutzung unserer AGB zu.</p></body></html>"))

这是我尝试运行的整个代码。由于任何原因,它没有显示纯文本,并给了我以下错误:

QPainter::setPen: Painter not active
QPainter::setBrush: Painter not active
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setPen: Painter not active
QPainter::setBrush: Painter not active
    

    # -*- coding: utf-8 -*-
    import sys, random
    from PyQt5 import QtWidgets, QtGui, QtCore
    from untitled3.mainwindow import Ui_MainWindow
    import json
    import requests

    app = QtWidgets.QApplication(sys.argv)

    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent = None):              
            super().__init__(parent)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
            #self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
            #self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
            self.willkommen()
        

    def willkommen(self, parent = None):
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(8)
        font.setStrikeOut(False)
        self.ui.textEdit.setLineWrapMode(self.ui.textEdit.LineWrapMode(3))        
        self.ui.textEdit.setLineWrapColumnOrWidth(40)
        self.ui.textEdit.setWordWrapMode(1)
        self.ui.textEdit.setFont(font)
        self.ui.textEdit.setPlainText("Willkommen. Ich bin Evossistant und beantworte Ihre Fragen.\
Bitte lesen Sie die AGB, bevor Sie den Chatbot nutzen.")
        self.ui.textEdit.append("")
        self.ui.textEdit.setAlignment(QtCore.Qt.AlignRight)
        self.ui.lineEdit.returnPressed.connect(self.ui.pushButton.click)
        self.ui.pushButton.clicked.connect(self.nutzereingabe)
        self.ui.textEdit.moveCursor(QtGui.QTextCursor.End)
        self.ui.textEdit.paintEvent = self.paintEvent(None)
        

    def paintEvent(self, event):        
        painter = QtGui.QPainter(self.ui.textEdit.viewport())    
        pen = QtGui.QPen(QtGui.QColor(143, 188, 143, 50))
        pen.setStyle(QtCore.Qt.SolidLine)
        pen.setCapStyle(QtCore.Qt.RoundCap)
        brush = QtGui.QBrush(QtGui.QColor(143, 188, 143, 50))
        painter.setPen(pen)
        painter.setBrush(brush)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        doc = self.ui.textEdit.document()
        margin = doc.documentMargin()
        rightAlignmentStart = self.ui.textEdit.size().width()
        natruralTextWidth = 0
        unitedBlockRect = QtCore.QRectF()
        for b in range(doc.blockCount()):
            block = doc.findBlockByNumber(b)
            blockRect = doc.documentLayout().blockBoundingRect(block)
            layout = block.layout()           
            lineRect = QtCore.QRectF()
            for k in range(layout.lineCount()):
                line = layout.lineAt(k)
                linerect = line.rect()
                naturalTextWidth = max(line.naturalTextWidth(), natruralTextWidth)
                #if self.ui.textEdit.alignment() == QtCore.Qt.AlignRight:         
                rightAlignmentStart = min(rightAlignmentStart, self.ui.textEdit.size().width() - naturalTextWidth - margin) 
                lineRect = lineRect.united(linerect)
            unitedBlockRect = blockRect.united(lineRect)    
        unitedBlockRect.setX(rightAlignmentStart - 20)       
        #I think it is better you keep a extra width.
        unitedBlockRect.setWidth(unitedBlockRect.width() )
        painter.drawRoundedRect(unitedBlockRect, 10, 10)        
        #return QtWidgets.QTextEdit.paintEvent(self, event)

    
    def nutzereingabe(self):
        text = self.ui.lineEdit.text()
        self.ui.lineEdit.clear()
        #self.ui.textEdit.setTextBackgroundColor(QtGui.QColor(176, 224, 230))
        self.ui.textEdit.setAlignment(QtCore.Qt.AlignLeft)
        self.ui.textEdit.append(text)
        self.ui.textEdit.append("")
        Dict_to_send = "sender": "user_name", "message": text
        print(Dict_to_send)
        self.request(Dict_to_send)

    
    def request(self,Dict_to_send):
    
        Url = "http://127.0.0.1:5005/webhooks/rest/webhook"
        r = requests.post(Url, json = Dict_to_send)
        print(r.text)
        b = r.text       
        if "text" in b:
            a = (b.strip('"]').split(":")[2])
            message = a.replace('"', "")
            self.botausgabe(message)
        else:
            message = "keine Antwort"
            self.botausgabe(message)

    def botausgabe(self, message):       
        #self.ui.textEdit.setTextBackgroundColor(QtGui.QColor(143,188,143))
        self.ui.textEdit.setAlignment(QtCore.Qt.AlignRight)
        self.ui.textEdit.append(message)
        self.ui.textEdit.append("")
       
window = MainWindow()
window.show()
sys.exit(app.exec_())

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:/Users/Polat/Desktop/ChatGUI/untitled3\mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.NonModal)
        MainWindow.setEnabled(True)
        MainWindow.resize(500, 600)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(300, 300))
        MainWindow.setMaximumSize(QtCore.QSize(700, 16777215))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(14)
        font.setStrikeOut(False)
        MainWindow.setFont(font)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../../Desktop/ChatbotProgrammierung/evocenta.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        MainWindow.setWindowOpacity(255.0)
        MainWindow.setAutoFillBackground(False)
        MainWindow.setStyleSheet("QMainWindow     \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 200));\n"
"\n"
"\n"
"QTabWidget     \n"
"    \n"
"    border:None;\n"
"\n"
"\n"
"QTabWidget::pane   \n"
"border: 0;    \n"
"\n"
"\n"
"\n"
"\n"
"\n"
"QWidget     \n"
"background-color: qlineargradient(spread:reflect, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 100), stop:0.88 rgba(255, 255, 255, 255), stop:0.92 rgba(75, 111, 180, 150), stop:0.96 rgba(148, 27, 128, 150), stop:1 rgba(231, 170, 0, 150));\n"
"\n"
"    Border:none;\n"
"    \n"
"\n"
"QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"\n"
"QPushButton\n"
"Border-radius: 10px;\n"
"QLineEdit\n"
"Border-radius: 10px;")
        MainWindow.setInputMethodHints(QtCore.Qt.ImhNone)
        MainWindow.setIconSize(QtCore.QSize(30, 30))
        MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
        MainWindow.setDockOptions(QtWidgets.QMainWindow.AllowTabbedDocks|QtWidgets.QMainWindow.AnimatedDocks)
        self.widget = QtWidgets.QWidget(MainWindow)
        self.widget.setEnabled(True)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy(sizePolicy)
        self.widget.setMinimumSize(QtCore.QSize(300, 300))
        self.widget.setStyleSheet("")
        self.widget.setObjectName("widget")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.frame = QtWidgets.QFrame(self.widget)
        self.frame.setEnabled(True)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setAutoFillBackground(False)
        self.frame.setStyleSheet("")
        self.frame.setInputMethodHints(QtCore.Qt.ImhNone)
        self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.frame.setObjectName("frame")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.frame)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.tabWidget = QtWidgets.QTabWidget(self.frame)
        self.tabWidget.setAutoFillBackground(False)
        self.tabWidget.setStyleSheet("QTabBar::tab    \n"
"background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    border-top-left-radius: 5px;\n"
"    border-top-right-radius: 5px;\n"
"    border-bottom-left-radius: 5px;\n"
"    border-bottom-right-radius: 5px;\n"
"    min-width: 14ex;\n"
"    padding: 2px;\n"
"\n"
"\n"
"QTabBar::tab:selected, QTabBar::tab:hover \n"
"    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
"                                stop: 0 #fafafa, stop: 0.4 #f4f4f4,\n"
"                                stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);\n"
"\n"
"")
        self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
        self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
        self.tabWidget.setElideMode(QtCore.Qt.ElideNone)
        self.tabWidget.setUsesScrollButtons(True)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setMovable(False)
        self.tabWidget.setTabBarAutoHide(False)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tab.sizePolicy().hasHeightForWidth())
        self.tab.setSizePolicy(sizePolicy)
        self.tab.setAutoFillBackground(False)
        self.tab.setStyleSheet("QWidget    \n"
"    background-color: rgba(255, 255, 255, 50);\n"
"    Border-radius: 10px;\n"
"")
        self.tab.setObjectName("tab")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.tab)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.frame_chat1 = QtWidgets.QFrame(self.tab)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_chat1.sizePolicy().hasHeightForWidth())
        self.frame_chat1.setSizePolicy(sizePolicy)
        self.frame_chat1.setStyleSheet("QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"")
        self.frame_chat1.setFrameShape(QtWidgets.QFrame.Box)
        self.frame_chat1.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_chat1.setObjectName("frame_chat1")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_chat1)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.textEdit = QtWidgets.QTextEdit(self.frame_chat1)
        self.textEdit.setStyleSheet("QTextEdit \n"
"    background-color: rgba(255, 255, 255, 100);\n"
"    border-color: rgb(105, 210, 255);\n"
"    border-radius: 10px;\n"
"\n"
"")
        self.textEdit.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.textEdit.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustIgnored)
        self.textEdit.setReadOnly(True)
        self.textEdit.setMarkdown("")
        self.textEdit.setObjectName("textEdit")
        self.horizontalLayout_2.addWidget(self.textEdit)
        self.verticalLayout_2.addWidget(self.frame_chat1)
        self.frame_chat2 = QtWidgets.QFrame(self.tab)
        self.frame_chat2.setMinimumSize(QtCore.QSize(0, 0))
        self.frame_chat2.setMaximumSize(QtCore.QSize(16777215, 50))
        self.frame_chat2.setStyleSheet("QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"\n"
"\n"
"")
        self.frame_chat2.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame_chat2.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_chat2.setObjectName("frame_chat2")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_chat2)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.frame_chat2)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setMinimumSize(QtCore.QSize(0, 30))
        self.lineEdit.setStyleSheet("QLineEdit \n"
"    background-color: rgba(255, 255, 255, 100);\n"
"    \n"
"")
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.pushButton = QtWidgets.QPushButton(self.frame_chat2)
        self.pushButton.setMinimumSize(QtCore.QSize(70, 30))
        self.pushButton.setStyleSheet("QPushButton \n"
"    background-color: rgba(115, 174, 76, 100);\n"
"    \n"
"")
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout_2.addWidget(self.frame_chat2)
        self.verticalLayout_5.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tab_2.sizePolicy().hasHeightForWidth())
        self.tab_2.setSizePolicy(sizePolicy)
        self.tab_2.setAutoFillBackground(False)
        self.tab_2.setStyleSheet("QWidget    \n"
"    background-color: rgba(255, 255, 255, 50);\n"
"    Border-radius: 10px;\n"
"")
        self.tab_2.setObjectName("tab_2")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.tab_2)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.frame_agb = QtWidgets.QFrame(self.tab_2)
        self.frame_agb.setStyleSheet("QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"")
        self.frame_agb.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame_agb.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_agb.setObjectName("frame_agb")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.frame_agb)
        self.verticalLayout.setObjectName("verticalLayout")
        self.textEdit_2 = QtWidgets.QTextEdit(self.frame_agb)
        self.textEdit_2.setAutoFillBackground(False)
        self.textEdit_2.setStyleSheet("QTextEdit \n"
"    background-color: rgba(255, 255, 255, 100);\n"
"    border-color: rgb(105, 210, 255);\n"
"    border-radius: 10px;\n"
"")
        self.textEdit_2.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.textEdit_2.setReadOnly(True)
        self.textEdit_2.setObjectName("textEdit_2")
        self.verticalLayout.addWidget(self.textEdit_2)
        self.horizontalLayout_5.addWidget(self.frame_agb)
        self.tabWidget.addTab(self.tab_2, "")
        self.horizontalLayout_4.addWidget(self.tabWidget)
        self.horizontalLayout_3.addWidget(self.frame)
        MainWindow.setCentralWidget(self.widget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Evosisstant - Your Digital Guide"))
        self.textEdit.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li  white-space: pre-wrap; \n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
"<h1 style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:xx-large; font-weight:600;\"><br /></h1></body></html>"))
        self.lineEdit.setPlaceholderText(_translate("MainWindow", "Schreiben Sie hier..."))
        self.pushButton.setText(_translate("MainWindow", "Senden"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Chat"))
        self.textEdit_2.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li  white-space: pre-wrap; \n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Mit der Nutzung Des Chatbots stimmen Sie der Nutzung unserer AGB zu.</p></body></html>"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Nutzungsbedingungen"))[![enter image description here][1]][1]![enter image description here][2]

【问题讨论】:

你能分享你的代码吗? 如果缺少任何东西,我会尽快分享 你能试着更好地解释一下自己吗?不清楚标题中的“背景边框”是什么意思,因为在问题的正文中,您还提到了“文本的背景形状”,我​​真的不明白您想要做什么。 感谢您的回复。我在设置的文本后面做了一个深绿色的背景。我想将它的形状从矩形更改为圆形。使背景形状具有圆形边框或圆形。我很抱歉我的英语不好 你的文字是否都采用了背景色,它的颜色是否完全一样? 【参考方案1】:

更新2

对不起,我误会了……你给了我完整的代码,我从来不知道。在这种情况下,即使我使用 installEventFilter,paint 的内容也会被你的 setStyleSheet 设置透支,所以开。

所以我发现我可以创建 QTextEdit 的子类,我做到了。 请重试我的代码。


好的,我看到你的更新了,我觉得你对eventFilter的系统理解不够。事件从父到子流。(在这种情况下,很容易说,(QObject)→QApplication→QMainWindow→QTextEdit )

通常,事件在类的子类中被直接覆盖。

因为要绘制QTextEdit的视口,所以必须重写QTextEdit的子类中的paintEvent。但是在这种情况下,你是用Qt-Designer制作的GUI。 您不能在QTextEdit 中编写覆盖paintEvent 的代码。

主要的方法是覆盖paintEvent获得相同的效果,为此,您可以安装eventFilter。在QMainWindow时,您可以更改事件流。这里,现在,我只在self.ui.textEdit的情况由 If obj is self.ui.textEdit 标志。

# -*- coding: utf-8 -*-
import sys, random
from PyQt5 import QtWidgets, QtGui, QtCore
import json
import requests




#we can override if this setting is !
class TextEdit(QtWidgets.QTextEdit):
    def __init__(self, parent=None):
        super(TextEdit, self).__init__(parent)
    def paintEvent(self, event):
        painter = QtGui.QPainter(self.viewport())    
        pen = QtGui.QPen(QtGui.QColor(143, 188, 143, 255))
        pen.setStyle(QtCore.Qt.SolidLine)
        pen.setCapStyle(QtCore.Qt.RoundCap)
        brush = QtGui.QBrush(QtGui.QColor(143, 188, 143, 255))
        painter.setPen(pen)
        painter.setBrush(brush)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        doc = self.document()
        margin = doc.documentMargin()
        rightAlignmentStart = self.size().width()
        natruralTextWidth = 0
        unitedBlockRect = QtCore.QRectF()
        for b in range(doc.blockCount()):
            block = doc.findBlockByNumber(b)
            blockRect = doc.documentLayout().blockBoundingRect(block)
            layout = block.layout()           
            lineRect = QtCore.QRectF()
            for k in range(layout.lineCount()):
                line = layout.lineAt(k)
                linerect = line.rect()
                naturalTextWidth = max(line.naturalTextWidth(), natruralTextWidth)
                #if self.ui.textEdit.alignment() == QtCore.Qt.AlignRight:         
                rightAlignmentStart = min(rightAlignmentStart, self.size().width() - naturalTextWidth - margin) 
                lineRect = lineRect.united(linerect)
            unitedBlockRect = blockRect.united(lineRect)    
        unitedBlockRect.setX(rightAlignmentStart - 20)       
        #I think it is better you keep a extra width.
        unitedBlockRect.setWidth(unitedBlockRect.width() )
        painter.drawRoundedRect(unitedBlockRect, 10, 10)    
        return QtWidgets.QTextEdit.paintEvent(self, event)
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.NonModal)
        MainWindow.setEnabled(True)
        MainWindow.resize(500, 600)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(300, 300))
        MainWindow.setMaximumSize(QtCore.QSize(700, 16777215))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(14)
        font.setStrikeOut(False)
        MainWindow.setFont(font)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../../Desktop/ChatbotProgrammierung/evocenta.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        MainWindow.setWindowOpacity(255.0)
        MainWindow.setAutoFillBackground(False)
        MainWindow.setStyleSheet("QMainWindow     \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 200));\n"
"\n"
"\n"
"QTabWidget     \n"
"    \n"
"    border:None;\n"
"\n"
"\n"
"QTabWidget::pane   \n"
"border: 0;    \n"
"\n"
"\n"
"\n"
"\n"
"\n"
"QWidget     \n"
"background-color: qlineargradient(spread:reflect, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 100), stop:0.88 rgba(255, 255, 255, 255), stop:0.92 rgba(75, 111, 180, 150), stop:0.96 rgba(148, 27, 128, 150), stop:1 rgba(231, 170, 0, 150));\n"
"\n"
"    Border:none;\n"
"    \n"
"\n"
"QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"\n"
"QPushButton\n"
"Border-radius: 10px;\n"
"QLineEdit\n"
"Border-radius: 10px;")
        MainWindow.setInputMethodHints(QtCore.Qt.ImhNone)
        MainWindow.setIconSize(QtCore.QSize(30, 30))
        MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
        MainWindow.setDockOptions(QtWidgets.QMainWindow.AllowTabbedDocks|QtWidgets.QMainWindow.AnimatedDocks)
        self.widget = QtWidgets.QWidget(MainWindow)
        self.widget.setEnabled(True)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy(sizePolicy)
        self.widget.setMinimumSize(QtCore.QSize(300, 300))
        self.widget.setStyleSheet("")
        self.widget.setObjectName("widget")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.frame = QtWidgets.QFrame(self.widget)
        self.frame.setEnabled(True)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setAutoFillBackground(False)
        self.frame.setStyleSheet("")
        self.frame.setInputMethodHints(QtCore.Qt.ImhNone)
        self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.frame.setObjectName("frame")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.frame)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.tabWidget = QtWidgets.QTabWidget(self.frame)
        self.tabWidget.setAutoFillBackground(False)
        self.tabWidget.setStyleSheet("QTabBar::tab    \n"
"background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    border-top-left-radius: 5px;\n"
"    border-top-right-radius: 5px;\n"
"    border-bottom-left-radius: 5px;\n"
"    border-bottom-right-radius: 5px;\n"
"    min-width: 14ex;\n"
"    padding: 2px;\n"
"\n"
"\n"
"QTabBar::tab:selected, QTabBar::tab:hover \n"
"    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
"                                stop: 0 #fafafa, stop: 0.4 #f4f4f4,\n"
"                                stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);\n"
"\n"
"")
        self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
        self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
        self.tabWidget.setElideMode(QtCore.Qt.ElideNone)
        self.tabWidget.setUsesScrollButtons(True)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setMovable(False)
        self.tabWidget.setTabBarAutoHide(False)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tab.sizePolicy().hasHeightForWidth())
        self.tab.setSizePolicy(sizePolicy)
        self.tab.setAutoFillBackground(False)
        self.tab.setStyleSheet("QWidget    \n"
"    background-color: rgba(255, 255, 255, 50);\n"
"    Border-radius: 10px;\n"
"")
        self.tab.setObjectName("tab")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.tab)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.frame_chat1 = QtWidgets.QFrame(self.tab)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_chat1.sizePolicy().hasHeightForWidth())
        self.frame_chat1.setSizePolicy(sizePolicy)
        self.frame_chat1.setStyleSheet("QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"")
        self.frame_chat1.setFrameShape(QtWidgets.QFrame.Box)
        self.frame_chat1.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_chat1.setObjectName("frame_chat1")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_chat1)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.textEdit = TextEdit(self.frame_chat1)
        self.textEdit.setStyleSheet("QTextEdit \n"
"    background-color: rgba(255, 255, 255, 100);\n"
"    border-color: rgb(105, 210, 255);\n"
"    border-radius: 10px;\n"
"\n"
"")
        self.textEdit.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.textEdit.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustIgnored)
        self.textEdit.setReadOnly(True)
        self.textEdit.setMarkdown("")
        self.textEdit.setObjectName("textEdit")
        self.horizontalLayout_2.addWidget(self.textEdit)
        self.verticalLayout_2.addWidget(self.frame_chat1)
        self.frame_chat2 = QtWidgets.QFrame(self.tab)
        self.frame_chat2.setMinimumSize(QtCore.QSize(0, 0))
        self.frame_chat2.setMaximumSize(QtCore.QSize(16777215, 50))
        self.frame_chat2.setStyleSheet("QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"\n"
"\n"
"")
        self.frame_chat2.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame_chat2.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_chat2.setObjectName("frame_chat2")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_chat2)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.frame_chat2)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setMinimumSize(QtCore.QSize(0, 30))
        self.lineEdit.setStyleSheet("QLineEdit \n"
"    background-color: rgba(255, 255, 255, 100);\n"
"    \n"
"")
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.pushButton = QtWidgets.QPushButton(self.frame_chat2)
        self.pushButton.setMinimumSize(QtCore.QSize(70, 30))
        self.pushButton.setStyleSheet("QPushButton \n"
"    background-color: rgba(115, 174, 76, 100);\n"
"    \n"
"")
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout_2.addWidget(self.frame_chat2)
        self.verticalLayout_5.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tab_2.sizePolicy().hasHeightForWidth())
        self.tab_2.setSizePolicy(sizePolicy)
        self.tab_2.setAutoFillBackground(False)
        self.tab_2.setStyleSheet("QWidget    \n"
"    background-color: rgba(255, 255, 255, 50);\n"
"    Border-radius: 10px;\n"
"")
        self.tab_2.setObjectName("tab_2")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.tab_2)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.frame_agb = QtWidgets.QFrame(self.tab_2)
        self.frame_agb.setStyleSheet("QFrame    \n"
"    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(115, 174, 76, 255), stop:1 rgba(255, 255, 255, 255));\n"
"    Border-radius: 10px;\n"
"")
        self.frame_agb.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame_agb.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_agb.setObjectName("frame_agb")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.frame_agb)
        self.verticalLayout.setObjectName("verticalLayout")
        self.textEdit_2 = QtWidgets.QTextEdit(self.frame_agb)
        self.textEdit_2.setAutoFillBackground(False)
        self.textEdit_2.setStyleSheet("QTextEdit \n"
"    background-color: rgba(255, 255, 255, 100);\n"
"    border-color: rgb(105, 210, 255);\n"
"    border-radius: 10px;\n"
"")
        self.textEdit_2.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.textEdit_2.setReadOnly(True)
        self.textEdit_2.setObjectName("textEdit_2")
        self.verticalLayout.addWidget(self.textEdit_2)
        self.horizontalLayout_5.addWidget(self.frame_agb)
        self.tabWidget.addTab(self.tab_2, "")
        self.horizontalLayout_4.addWidget(self.tabWidget)
        self.horizontalLayout_3.addWidget(self.frame)
        MainWindow.setCentralWidget(self.widget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Evosisstant - Your Digital Guide"))
        self.textEdit.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li  white-space: pre-wrap; \n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
"<h1 style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:xx-large; font-weight:600;\"><br /></h1></body></html>"))
        self.lineEdit.setPlaceholderText(_translate("MainWindow", "Schreiben Sie hier..."))
        self.pushButton.setText(_translate("MainWindow", "Senden"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Chat"))
        self.textEdit_2.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li  white-space: pre-wrap; \n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:7.8pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Mit der Nutzung Des Chatbots stimmen Sie der Nutzung unserer AGB zu.</p></body></html>"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Nutzungsbedingungen"))
        
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent = None):              
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        #self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.willkommen()
        

    def willkommen(self, parent = None):
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(8)
        font.setStrikeOut(False)
        self.ui.textEdit.setLineWrapMode(self.ui.textEdit.LineWrapMode(3))        
        self.ui.textEdit.setLineWrapColumnOrWidth(40)
        self.ui.textEdit.setWordWrapMode(1)
        self.ui.textEdit.setFont(font)
        self.ui.textEdit.setPlainText("Willkommen. Ich bin Evossistant und beantworte Ihre Fragen.\
    Bitte lesen Sie die AGB, bevor Sie den Chatbot nutzen.")
        self.ui.textEdit.append("")
        self.ui.textEdit.setAlignment(QtCore.Qt.AlignRight)
        self.ui.lineEdit.returnPressed.connect(self.ui.pushButton.click)
        self.ui.pushButton.clicked.connect(self.nutzereingabe)
        self.ui.textEdit.moveCursor(QtGui.QTextCursor.End)
    
        
 
    
    def nutzereingabe(self):
        text = self.ui.lineEdit.text()
        self.ui.lineEdit.clear()
        #self.ui.textEdit.setTextBackgroundColor(QtGui.QColor(176, 224, 230))
        self.ui.textEdit.setAlignment(QtCore.Qt.AlignLeft)
        self.ui.textEdit.append(text)
        self.ui.textEdit.append("")
        Dict_to_send = "sender": "user_name", "message": text
        print(Dict_to_send)
        self.request(Dict_to_send)
    
    
    def request(self,Dict_to_send):
    
        Url = "http://127.0.0.1:5005/webhooks/rest/webhook"
        r = requests.post(Url, json = Dict_to_send)
        print(r.text)
        b = r.text       
        if "text" in b:
            a = (b.strip('"]').split(":")[2])
            message = a.replace('"', "")
            self.botausgabe(message)
        else:
            message = "keine Antwort"
            self.botausgabe(message)
    
    def botausgabe(self, message):       
        #self.ui.textEdit.setTextBackgroundColor(QtGui.QColor(143,188,143))
        self.ui.textEdit.setAlignment(QtCore.Qt.AlignRight)
        self.ui.textEdit.append(message)
        self.ui.textEdit.append("")

def main():
    app = QtWidgets.QApplication(sys.argv) if QtWidgets.QApplication.instance() is None else QtWidgets.QApplication.instance()
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())
if __name__ == "__main__":
    main()

更新: 如果你想用气泡样式包裹所有文本,请将之前的代码替换为这个。


#it may be necessary to call repaint() at an appropriate time.
def paintEvent(self, event):        
        painter = QtGui.QPainter(self.viewport())    
        pen = QtGui.QPen(QtGui.QColor(143, 188, 143))
        pen.setStyle(QtCore.Qt.SolidLine)
        pen.setCapStyle(QtCore.Qt.RoundCap)
        brush = QtGui.QBrush(QtGui.QColor(143, 188, 143))
        painter.setPen(pen)
        painter.setBrush(brush)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        doc = self.document()
        margin = doc.documentMargin()
        rightAlignmentStart = self.size().width()
        natruralTextWidth = 0
        unitedBlockRect = QtCore.QRectF()
        for b in range(doc.blockCount()):
            block = doc.findBlockByNumber(b)
            blockRect = doc.documentLayout().blockBoundingRect(block)
            layout = block.layout()           
            lineRect = QtCore.QRectF()
            for k in range(layout.lineCount()):
                line = layout.lineAt(k)
                linerect = line.rect()
                naturalTextWidth = max(line.naturalTextWidth(), natruralTextWidth)
                if self.alignment() == QtCore.Qt.AlignRight:         
                    rightAlignmentStart = min(rightAlignmentStart, self.size().width() - naturalTextWidth - margin) 
                lineRect = lineRect.united(linerect)
            unitedBlockRect = blockRect.united(lineRect)    
        unitedBlockRect.setX(rightAlignmentStart - 20)       
        #I think it is better you keep a extra width.
        unitedBlockRect.setWidth(unitedBlockRect.width() )
        painter.drawRoundedRect(unitedBlockRect, 10, 10)        
        return QtWidgets.QTextEdit.paintEvent(self, event)

为用户界面

改变自己。 → 物件。或 self.ui.textEdit


请试试这个代码。

你设法绘制了圆角矩形背景。

但我现在能控制的范围如下:

    背景颜色被周围的文字所采用。 颜色相同。

如果您更改某些内容,您可能必须每次都考虑编码。

请将代码停靠在您的代码上。

注意:

line.rect() 返回QTextLine 的相对矩形。左上角是 (0, 0)。 如果我们按原样使用这个矩形,我们不能从第二个块中绘制适当的矩形。 所以我也得到了blockBoundingRect 并翻译了lineRect。这个rec​​t包含documentMargin。

  # -*- coding: utf-8 -*-
"""
Created on Sat Jan  2 12:26:06 2021

@author: Haru
"""
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class MyEdit(QtWidgets.QTextEdit):
    def __init__(self, parent=None):
        super(MyEdit, self).__init__(parent)
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(8)
        font.setStrikeOut(False)
        #You don't use setBackgroundColor()
        self.setLineWrapMode(self.LineWrapMode(3))        
        self.setLineWrapColumnOrWidth(40)
        self.setWordWrapMode(1)
        self.append("")
        self.setFont(font)
        self.setPlainText( "Here is the background i want to change. Iwant it to be round instead of a corner.")
        self.setAlignment(QtCore.Qt.AlignRight)
        
    def paintEvent(self, event):        
        painter = QtGui.QPainter(self.viewport())
        pen = QtGui.QPen(QtGui.QColor(143, 188, 143))
        pen.setStyle(QtCore.Qt.SolidLine)
        pen.setCapStyle(QtCore.Qt.RoundCap)
        brush = QtGui.QBrush(QtGui.QColor(143, 188, 143))
        painter.setPen(pen)
        painter.setBrush(brush)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        doc = self.document()
        margin = doc.documentMargin()
        for b in range(doc.blockCount()):
            block = doc.findBlockByNumber(b)
            blockRect = doc.documentLayout().blockBoundingRect(block)
            layout = block.layout()           
            for k in range(layout.lineCount()):
                line = layout.lineAt(k)
                lineRect = line.rect()
                lineRect.setWidth(line.naturalTextWidth())
                lineRect.translate(blockRect.x(), blockRect.y())
                if self.alignment() == QtCore.Qt.AlignRight:                    
                    lineRect.setX(self.size().width() - line.naturalTextWidth() - margin)
                    lineRect.setWidth(line.naturalTextWidth())
                painter.drawRoundedRect(lineRect, 2, 2)  
        return QtWidgets.QTextEdit.paintEvent(self, event)

我的代码结果(在我的环境中)

因为您是由 Qt-designer 制作的小部件,所以您可能无法按原样停靠我的代码。 这是代码。请重写必要的部分。 ThisClassName,等等。

self.ui.textEdit.installEventFilter(self)

def eventFilter(self, obj, event):
    if event.type() == QtCore.QEvent.Paint:
        if obj is self.ui.textEdit:
            painter = QtGui.QPainter(obj.viewport())
            pen = QtGui.QPen(QtGui.QColor(143, 188, 143))
            pen.setCapStyle(QtCore.Qt.RoundCap)
            brush = QtGui.QBrush(QtGui.QColor(143, 188, 143))
            painter.setPen(pen)
            painter.setBrush(brush)
            painter.setRenderHint(QtGui.QPainter.Antialiasing)
            doc = obj.document()
            margin = doc.documentMargin()
            for b in range(doc.blockCount()):
                block = doc.findBlockByNumber(b)
                blockRect = doc.documentLayout().blockBoundingRect(block)
                layout = block.layout()           
                for k in range(layout.lineCount()):
                    line = layout.lineAt(k)
                    lineRect = line.rect()
                    lineRect.setWidth(line.naturalTextWidth())
                    lineRect.translate(blockRect.x(), blockRect.y())
                    if self.alignment() == QtCore.Qt.AlignRight:                    
                        lineRect.setX(obj.size().width() - line.naturalTextWidth() - margin)
                        lineRect.setWidth(line.naturalTextWidth())
                    painter.drawRoundedRect(lineRect, 2, 2)  
             return True
    return  **ThisClassName**.eventFilter(self, obj, event)

【讨论】:

if not painter.isActive() 没用,只需创建以目标对象为参数的painter即可;此外,QBrush 始终默认使用 SolidPattern,并且在绘制事件中无需结束绘制器,因为它会在对象销毁时自动关闭。 您的评论非常棒。好的,我会重新编辑。 不要调用painter.begin(self.viewport()),只创建painter = QPainter(self.viewport()) 抱歉,这是不正确的:如果您使用目标设备作为参数创建画家,则不应调用 begin,因为创建这样的实例会自动开始绘画操作。 如果你没问题,请随意改写我的答案。我相信你。

以上是关于无法在 Pyqt5 中更改 qtextedit 的背景边框,有啥建议吗?的主要内容,如果未能解决你的问题,请参考以下文章

PyQt5 从主模块外部实时登录 QTextedit

python pyqt5 QTextEdit 多行文本框

PyQt5 - 滚动到 QTextEdit 的光标

PyQt5 控件学习(一个一个学习之QPlainTextEdit)

无法在 Pyqt5 的 Qtext 编辑中使用 jinja2 设置表格的 CSS(文本换行和水平滚动条)

QTextEdit 不设置文本