2017-05-23 30 views
0

我創建一個QTextBrowser在我的代碼中顯示一個html表。但是當我嘗試使用setTextCursor方法將光標移動到特定行時,它未能做到這一點。如何將QTextBrowser的遊標(包含一個html表格)移動到PyQt5中的特定行?

文本瀏覽器的滾動條確實移動了,但沒有移動到特定的行。這個問題與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_()) 

回答

0

經過一番艱難的,我發現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_numTD標籤表的每一行中的數量。

相關問題