How in pyqt change text in QPlainTextEdit() if sli

2020-04-02 07:09发布

问题:

message = QtGui.QPlainTextEdit()
slider = QtGui.QSlider()
def slider_func():
    if slider.value() == 0:
       '''what to write here ?'''

    if slider.value() == 1:
        m = str(message.toPlainText())
        translated = ''
        i = len(m) - 1
        while i >= 0:
            translated = translated + m[i]
            i = i - 1
        message.setPlainText(translated)
QtCore.QObject.connect(slider, QtCore.SIGNAL('valueChanged(int)'),
                    slider_func)

When I set slider to the first tick, the text gets reversed. But when I set it to the begining the text is still reversed. I know that the problem is that once the text was changed it sets the text edit line. Any ideas how to solve it ? Example1, Example2

回答1:

Here is an example of how to watch the value of the slider, and modify a QPlainText when the value is at certain values.

from PyQt4.QtGui import *
from PyQt4.Qt import *
import sys


class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.text = "Please enter some text"
        self.edit = QPlainTextEdit(self.text)
        layout.addWidget(self.edit)

        slider = QSlider(Qt.Horizontal)
        layout.addWidget(slider)
        slider.valueChanged.connect(self.change_value)

    def change_value(self, value):
        if value == 0:
            self.edit.setPlainText(self.text)
        elif value == 1:
            self.edit.setPlainText(self.text[::-1])
        elif value > 1:
            self.edit.setPlainText("Slider value is above 1, value: {0}".format(value))


app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())

When the QSlider.valueChanged signal is emitted, the new value is carried with it. So in my slot Window.change_value(self, value) the value positional argument will always contain the new QSlider value; which allows you to test against it.