K
K
Kurum2018-04-30 12:47:58
Python
Kurum, 2018-04-30 12:47:58

Pyqt4 | How to get next search result in QTextEdit?

How to find the following text search results?

# Python 3
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import (QWidget, qApp, QAction, QApplication, QHBoxLayout, QVBoxLayout,
                             QGridLayout, QLabel, QLineEdit, QTextEdit, QPushButton, QComboBox,
                             QCheckBox, QRadioButton, QFrame, QScrollArea, QTabWidget, QSizePolicy,
                             QGroupBox, QFileDialog)
from PyQt4.QtGui import QIcon, QPixmap, QPalette, QTextCursor
from PyQt4.QtCore import QSize
tx = '''Константин бежал по дорожке, а потом колол дрова.
Кондрат собирал корения. На улице стоял колотун.
Иван же лежал в гамаке и пил кофе с конфетами.
ваер  р
вп
фп пр
ко
афвп
ырап
авпопр
рпавап
фпре
ре р пар
ер екр
рвек'''
# ЦВЕТА ПОЛЕЙ
sss_vivod = ("background-color: #456173; color: #f2f2f0; font: 14pt 'Courier New'")
# ГРАФИКА
class Window(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.resize(600, 250) # шир / выс окна
        self.setWindowTitle('Поиск текста') # Заголовок
        # ПЕРЕМЕННЫЕ КЛАССА
        self.find_index = 0
        # БЛОК РАЗМЕТКИ
        #grid_os = QGridLayout()
        vbox = QVBoxLayout()
        # ---
        self.pole_vivod = QTextEdit('')
        self.pole_vivod.setStyleSheet(sss_vivod)
        self.pole_vivod.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction) # QtCore.Qt.TextEditorInteraction
        vbox.addWidget(self.pole_vivod)
        # ---
        grid_UT = QGridLayout()
        vbox.addLayout(grid_UT)
        # --- --- поиск ---
        self.btn_find_clear = QtGui.QPushButton('X')
        self.btn_find_clear.clicked.connect(self.on_find_clear)
        grid_UT.addWidget(self.btn_find_clear, 1,0)
        # ---
        self.btn_find_backward = QtGui.QPushButton('◄')
        self.btn_find_backward.clicked.connect(self.on_find_backward)
        grid_UT.addWidget(self.btn_find_backward, 1,1)
        # ---
        self.btn_find_forward = QtGui.QPushButton('►')
        self.btn_find_forward.clicked.connect(self.on_find_forward)
        grid_UT.addWidget(self.btn_find_forward, 1,2)
        # ---
        self.pole_find = QLineEdit(self)
        self.pole_find.setToolTip('Поиск текста')
        self.pole_find.textChanged.connect(self.on_find_text)
        grid_UT.addWidget(self.pole_find, 1,3,1,10)
        # настройка:
        grid_UT.setColumnStretch(10, 1)
        for i in range(10):
            grid_UT.setColumnMinimumWidth(i, 10) # индекс / высота
        # --- --- end: поиск ---
        
        # ---
        self.setLayout(vbox)
        # --- ---
        Window.on_start(self)
    # ЛОГИКА
    
    def on_start(self):        
        self.pole_vivod.append(str(tx))
        self.pole_vivod.moveCursor(QtGui.QTextCursor.Start)
    # === >>> ПОИСК ТЕКСТА ===
    def on_find_text(self):
        # self.find_index # как-то использовать для списка найденных индексов
        text = self.pole_find.text()
        self.pole_vivod.moveCursor(QtGui.QTextCursor.Start)
        self.pole_vivod.find(text)
    def on_find_forward(self): # поиск вперёд
        self.find_index += 1
        self.on_find_text()
    def on_find_backward(self): # поиск назад
        self.find_index -= 1
        self.on_find_text()
    def on_find_clear(self): # очистить поиск
        self.find_index = 0
        self.pole_find.blockSignals(1) # блокировка сигналов
        self.pole_find.clear()
        self.pole_find.blockSignals(0) # отмена блокировки сигналов
        cursor = self.pole_vivod.textCursor()
        posit = cursor.position() # позиц курсора
        cursor.movePosition(posit) # происходит сброс выделения        
        self.pole_vivod.setTextCursor(cursor)
        
    # === >>> END: ПОИСК ТЕКСТА === 
# КОНЕЦ
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = Window()   
    window.show()
    sys.exit(app.exec_())

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question