下面是我的示例代码:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(691, 327)
self.listWidget = QtWidgets.QListWidget(Form)
self.listWidget.setGeometry(QtCore.QRect(70, 40, 256, 192))
self.listWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.listWidget.setObjectName("listWidget")
self.plainTextEdit = QtWidgets.QPlainTextEdit(Form)
self.plainTextEdit.setGeometry(QtCore.QRect(360, 40, 261, 191))
self.plainTextEdit.setTabChangesFocus(True)
self.plainTextEdit.setReadOnly(True)
self.plainTextEdit.setObjectName("plainTextEdit")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
lists = ["one","two","Three"]
for i in lists:
item = QtWidgets.QListWidgetItem(i)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listWidget.addItem(item)
self.listWidget.itemClicked.connect(self.on_listWidget_itemClicked)
def on_listWidget_itemClicked(self, item):
lines = self.plainTextEdit.toPlainText()
line_list = []
#if item.listWidget().itemWidget(item) != None:
if item.checkState() == QtCore.Qt.Checked:
self.plainTextEdit.appendPlainText(item.text())
elif item.checkState() == QtCore.Qt.Unchecked:
print(item.text())
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
在这个例子中,我将 QListWidget 与 ItemIsUserCheckable 和 QPlainTextEdit 一起使用。我能够使用复选框从 Qlistwidget 获取项目到 QPlainTextEdit。如果我检查 Qlistwidget 中的项目,它可以将文本设置为 QPlaintextEdit。但是当我取消选中项目框时,我想删除或删除 QplainTextEdit 中的相同文本。例如,如果我在 Qlistwidget “one”中选中该项目,它会将“one”设置为 QplainTextEdit,并且当我取消选中该项目时应该删除相同的项目。如果可以的话,有可能怎么办?