如何在pyqt5中使用QTextEdit来显示html的所有样式(包括css的样式)

2024-06-25 05:43:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 3.6 PYQT 5.12.1

我已经准备好用pyqt5展示我需要的样式,而且我知道pyqt5中的QTextEdit可以很好地显示html代码(我有一些web开发经验),所以我决定使用html/css来显示我的风格。但是,在用css显示代码时可能会有一些问题。我该怎么做才能让它显示css/javascript?如果不能,可以推荐其他方法修改样式吗?在

当我用html编码时,它可以显示一些样式,比如width = "100" height = "100",而不是css,还有一些不能像border-radius:50%;那样显示。当我用css编写样式时,它不会得到任何效果。顺便说一下,我已经导入了CSS代码。 CSS代码在QTextEdit中什么也不做(但在html中是可以的)

.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class WINDOW(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init()

    def init(self):
        w_width,w_height,w_x,w_y  = 700,640,700,200
        self.set_size_pos(w_width,w_height,w_x,w_y);
        self.set_message_textedit()
        self.message_textedit.setHtml(self.get_html())        
        self.show()

    def set_size_pos(self,width,height,x,y):
        '''
        set window's width , height and position
        '''
        self.resize(width,height)
        self.move(x,y)

    def set_message_textedit(self):
        self.message_textedit = QTextEdit(self)
        self.message_textedit.setFont(QFont("Microsoft YaHei",12))
        self.message_textedit.resize(680,420)
        self.message_textedit.move(10,50)
        self.message_textedit.setReadOnly(True)

    def get_html(self):
        html = ""
        with open("./chat-style/chat.html","r",encoding = "utf-8") as f:
            html = f.read()
        return html

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = WINDOW()
    sys.exit(app.exec_())

.html

^{pr2}$

.css

.tx
{        
    border-radius:50%;
    width:  30;
    height: 30;
}

Tags: 代码importselfmessageinitdefhtmlsys
1条回答
网友
1楼 · 发布于 2024-06-25 05:43:52

QTextEdit只支持css2.1,如the docs所示:

All CSS 2.1 selector classes are supported except pseudo-class selectors such as :first-child, :visited and :hover.

但是在CSS3中引入了{}。所以你不能不幸地使用它。我建议您阅读以下链接,以便了解允许的标记。在

另一种选择是使用支持这些标记的QWebEngineView:

*.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        view = QtWebEngineWidgets.QWebEngineView()
        file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 
            "chat-style/chat.html"
        )
        view.load(QtCore.QUrl.fromLocalFile(file))
        self.setCentralWidget(view)
        self.resize(640, 480)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

如果未安装QWebEngineView,则必须使用以下命令进行安装:

^{pr2}$

相关问题 更多 >