我想将文件拖放到listwidget
上,然后在itemactivated
,plaintextedit
打开并在文件中插入readAll
行时。但返回错误:"connect() failed between itemActivated(QListWidgetItem*) and read_txt()"
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(873, 663)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.listWidget = listWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(150, 330, 256, 192))
self.listWidget.setObjectName("listWidget")
self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)
self.plainTextEdit.setGeometry(QtCore.QRect(440, 200, 104, 87))
self.plainTextEdit.setObjectName("plainTextEdit")
self.listWidget.itemActivated.connect(self.read_txt)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
@QtCore.pyqtSlot("QListWidgetItem*")
def read_txt(self,links):
file = QtCore.QFile(links.text())
if file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
self.plainTextEdit.setPlainText(file.readAll().data().decode())
class listWidget(QtWidgets.QListWidget):
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.acceptProposedAction()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.acceptProposedAction()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
for url in event.mimeData().urls():
links=QtWidgets.QListWidgetItem(url.toLocalFile())
self.addItem(links)
event.acceptProposedAction()
if __name__ == "__main__":
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
app.exec_()
拖放工作正常,但无法使用QListWidgetItem
中的readtxt
方法连接setupUi
。有什么问题??
答案 0 :(得分:0)
问题是@pyqtSlot
装饰器只能用于从QObject
继承的类中。您可以将信号连接到任何可调用对象,因此最简单的方法就是省略装饰器,但是如果出于某种原因确实需要装饰器,则可以继承QMainWindow
并在其中定义插槽,例如
class MyMainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.listWidget.itemActivated.connect(self.read_txt)
@QtCore.pyqtSlot("QListWidgetItem*")
def read_txt(self, links):
file = QtCore.QFile(links.text())
if file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
self.ui.plainTextEdit.setPlainText(file.readAll().data().decode())
if __name__ == '__main__':
...
mainWindow = MyMainWindow()
mainWindow.show()
...