【问题标题】:How to get selected text and start and end locations using PySide & QTextEdit?如何使用 PySide 和 QTextEdit 获取选定的文本以及开始和结束位置?
【发布时间】:2017-09-18 06:59:38
【问题描述】:

我能够显示 QTextEdit 小部件并检测用户何时更改所选文本。但是,我不确定如何获取选定的文本以及表示选择的开始和结束位置的整数值,以从文本字段开头开始的字符数来衡量。我需要创建一个 QTextCursor 吗?我会很感激一个例子。这是我当前的代码:

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_())

【问题讨论】:

    标签: python qt pyside


    【解决方案1】:

    您可以通过QTextCursorQTextEdit 中进行选择,是的。它有你应该使用的selectionStartselectionEnd 方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2012-01-25
      相关资源
      最近更新 更多