2017-09-18 33 views
0

我可以顯示一個QTextEdit小部件並檢測用戶何時更改所選文本。但是,我不確定如何將選定文本和表示測量選擇開始和結束位置的整數值作爲文本字段開始處的字符數。我是否需要創建一個QTextCursor?我會欣賞一個例子。這裏是我當前的代碼:如何使用PySide&QTextEdit獲取選定的文本和開始和結束位置?

import sys 
from PySide.QtCore import * 
from PySide.QtGui import * 

class Form(QDialog): 
    def __init__(self, parent=None): 
     super(Form, self).__init__(parent) 
     self.setWindowTitle("My Form") 
     self.edit = QTextEdit("Type here...") 
     self.button = QPushButton("Show Greetings") 
     self.button.clicked.connect(self.greetings) 
     self.quit = QPushButton("QUIT") 
     self.quit.clicked.connect(app.exit) 
     self.edit.selectionChanged.connect(self.handleSelectionChanged) 

     layout = QVBoxLayout() 
     layout.addWidget(self.edit) 
     layout.addWidget(self.button) 
     layout.addWidget(self.quit) 
     self.setLayout(layout) 

    def greetings(self): 
     print ("Hello %s" % self.edit.text()) 

    def handleSelectionChanged(self): 
     print ("Selection start:%d end%d" % (0,0)) # change to position & anchor 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    form=Form() 
    form.show() 
    sys.exit(app.exec_()) 

回答

1

您可以選擇內QTextEdit通過QTextCursor工作,是的。它有selectionStartselectionEnd您應該使用的方法:

def handleSelectionChanged(self): 
    cursor = self.edit.textCursor() 
    print ("Selection start: %d end: %d" % 
      (cursor.selectionStart(), cursor.selectionEnd())) 
+0

謝謝。這是我需要的幫助!有用。 – davideps

相關問題