如何在TextEdit中使用文本并对其进行更改?类似于我的代码,查看它并告诉我在-btn_func-函数中可以做什么?

2024-10-01 05:05:30 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 当我按下按钮,删除QTextEdit中的所有空行时,我可以在这里写什么
  2. 我该怎么做:

文本编辑器中的文本:

Hello
Goodbye
Jack
Max

现在当我按下按钮插入12之后或之前:

Hello12
Goodbye12
Jack12
Max12

代码:

from PyQt5.QtWidgets import (QPushButton,QApplication,QWidget,QTextEdit,QVBoxLayout)
import sys

class MyApp(QWidget):
    def __init__ (self):
        super().__init__()
        self.initUI()
    def initUI(self):
        self.btn = QPushButton('MyFirstButton',self)
        self.vbox = QVBoxLayout(self)
        self.txt_ed = QTextEdit(self)
        self.vbox.addWidget(self.txt_ed)
        self.vbox.addWidget(self.btn)

        self.btn.clicked.connect(self.btn_func)

        self.setGeometry(300,300,300,450)
        self.setWindowTitle('MyTextApp')
        self.show()

    def btn_func(self):
        pass
        #? 1-What can I write here to when I pressed the button , delete all blank lines in QTextEdit
        #? 2. How can I do this:

        #text in TextEditor:
        #Hello
        #Goodbye
        #Jack
        #Max
        #-----------------------------
        #now when I pressed the button:
        #Hello12
        #Goodbye12
        #Jack12
        #Max12
        #-----------------------------
        #insert 12 after or before.
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Tags: selfhellodefsys按钮maxjackvbox
1条回答
网友
1楼 · 发布于 2024-10-01 05:05:30
  1. 删除所有空行
import re

# ...
class MyApp(QWidget):
    # ...
    def btn_func(self):
        original = self.txt_ed.toPlainText().split('\n')
        # https://stackoverflow.com/a/3711884
        filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
        self.txt_ed.setPlainText("\n".join(filtered))

  1. 在每行末尾插入“12”
def btn_func(self):
    lines = self.txt_ed.toPlainText().split('\n')
    word = "12"
    new_lines = [text + word for text in lines]
    self.txt_ed.setPlainText("\n".join(new_lines))

相关问题 更多 >