因为我不能在这里写完整的代码,所以我用同样的问题简化了它。
简化的程序是python代码连接一个ui文件,即:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>275</width>
<height>267</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QTextBrowser" name="textBrowser">
<property name="geometry">
<rect>
<x>10</x>
<y>50</y>
<width>256</width>
<height>192</height>
</rect>
</property>
</widget>
<widget class="QPushButton" name="OkButton">
<property name="geometry">
<rect>
<x>110</x>
<y>10</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Ok</string>
</property>
</widget>
<widget class="QPushButton" name="UndoButton">
<property name="geometry">
<rect>
<x>190</x>
<y>10</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Undo</string>
</property>
</widget>
<widget class="QTextEdit" name="textEdit">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>91</width>
<height>31</height>
</rect>
</property>
<property name="html">
<string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Gulim'; font-size:9pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">1</p></body></html></string>
</property>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
看起来像:
简化的python文件是:
import sys
import os
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5 import QtGui
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
form_class = uic.loadUiType(BASE_DIR + "./tester2.ui")[0]
class WindowClass(QMainWindow, form_class) :
def __init__(self) :
super().__init__()
self.setupUi(self)
self.OkButton.clicked.connect(self.Do_Append)
self.UndoButton.clicked.connect(self.Do_Undo)
def Do_Append(self):
data = self.textEdit.toPlainText()
self.textBrowser.append(data)
self.textBrowser.append('Test command')
self.textBrowser.append('\n')
def Do_Undo(self):
cursor = self.textBrowser.textCursor()
cursor.movePosition(QtGui.QTextCursor.StartOfLine)
cursor.select(QtGui.QTextCursor.LineUnderCursor)
cursor.removeSelectedText()
cursor.movePosition(QtGui.QTextCursor.End)
if __name__ == "__main__" :
app = QApplication(sys.argv)
myWindow = WindowClass()
myWindow.show()
app.exec_()
当您单击确定按钮时,此代码会将输入字符串写入文本浏览器。如果单击“撤消”按钮,我会尝试仅删除最新的两行。
我发现了 QTextCursor 并使用了它(StartOfLine、Up、StartofBlock、PreviousBlock、LineUnderCursor、BlockUnderCursor ......),但我不能做我想做的事,因为我只能擦除一行。我认为问题是关于 enter ( \n
) 但我无法解决问题。
我能做些什么来解决这个问题?