【问题标题】:How to move the cursor of a QTextBrowser(with an html table in it) to a specific line in PyQt5?如何将 QTextBrowser(其中包含 html 表)的光标移动到 PyQt5 中的特定行?
【发布时间】:2017-05-23 11:28:15
【问题描述】:

我创建了一个 QTextBrowser 来在我的代码中显示一个 html 表格。但是当我尝试使用 setTextCursor 方法将光标移动到特定行时,它没有做到这一点。

文本浏览器的滚动条确实移动了,但没有移动到特定的行。这个问题是不是和html表有关?

import sys
from PyQt5.QtGui import QTextCursor
from PyQt5.QtWidgets import QWidget, QTextBrowser, QMainWindow, QPushButton, QHBoxLayout, QApplication

class MyTextBrowser(QTextBrowser):

    def __init__(self, parent = None):
        super(MyTextBrowser, self).__init__(parent)
        self.createTable()

    def createTable(self, line_num = 1):
        # Create an html table with 100 lines
        html = '<table><tbody>'
        for i in range(0, 100):
            # Highlight specified line
            if line_num == i+1:
                html += '<tr style="background-color: #0000FF;"><td>Line</td><td>%d</td></tr>' % (i+1)
            else:
                html += '<tr><td>Line</td><td>%d</td></tr>' % (i+1)
        html += '</tbody></table>'
        self.setHtml(html)

        # Move the cursor to the specified line
        cursor = QTextCursor(self.document().findBlockByLineNumber(line_num))
        self.setTextCursor(cursor)

class MyWindow(QMainWindow):

    def __init__(self, parent = None):
        super(MyWindow, self).__init__(parent)
        self.createLayout()

    def createLayout(self):
        # Create the text browser and a button
        self.textBrowser = MyTextBrowser()
        self.button = QPushButton('Move cursor')
        self.button.clicked.connect(self.buttonClicked)
        self.currentLine = 1

        layout = QHBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.textBrowser)

        window = QWidget()
        window.setLayout(layout)
        self.setCentralWidget(window)

    def buttonClicked(self):
        # Move the cursor down for 10 lines when the button is clicked
        self.currentLine += 10
        if self.currentLine > 100:
            self.currentLine = 1

        self.textBrowser.createTable(self.currentLine)

app = QApplication(sys.argv)
window = MyWindow()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())

【问题讨论】:

    标签: python qt pyqt


    【解决方案1】:

    经过一番尝试,我发现 QTextBrowser 似乎将每个 td 标记视为一个新行。

    所以,而不是使用

    cursor = QTextCursor(self.document().findBlockByLineNumber(line_num))
    self.setTextCursor(cursor)
    

    我们应该使用

    cursor = QTextCursor(self.document().findBlockByLineNumber(line_num * td_num))
    self.setTextCursor(cursor)
    

    其中td_num是表格每一行中td标签的数量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 2018-08-05
      • 2022-01-23
      相关资源
      最近更新 更多