2017-09-18 9 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

[はい、QTextCursor経由QTextEdit以内に選択して作業することができます。 selectionStartselectionEndの方法をお使いください。

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

ありがとうございます。それが私の必要な助けです!できます。 – davideps

関連する問題