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

相关问题