我用QT-Designer创建了一个xml文件,其中包含一个LineEdit小部件。在我试图通过拖放发出文件路径的脚本中。它的工作,但圣。是错误的:将URL两次发射,看起来像:qt + pyqt发出丢弃的URL两次
/d:/ Qtfile:/// d:/ QT
我知道类似的主题,如PyQt event emmitted twice在计算器进行了讨论。但我找不到我的答案......也许我很想念它。为什么两次?为什么第一个“file://”消失了?
如果我不使用Qt-Designer并定义一个子类来拖放像类CustomEditLine(QLineEdit)这样的文本:...然后在主窗口中创建QlineEdit的实例,那么url只会被发射一次但仍然是“/ D:/ Qt”。 这里是我的代码:
from PyQt5 import QtWidgets, uic
from PyQt5.QtCore import QObject,QEvent
import sys
qtCreatorFile=".\\gui\\testdrop.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class QDropHandler(QObject):
def __init__(self, parent=None):
super(QDropHandler, self).__init__(parent)
def eventFilter(self, obj, event):
if event.type() == QEvent.DragEnter:
event.accept()
if event.type() == QEvent.Drop:
md = event.mimeData()
if md.hasUrls():
for url in md.urls():
obj.setText(url.path())
break
event.accept()
return False
class root_App(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(root_App, self).__init__()
self.setupUi(self)
self.lineEdit_1.installEventFilter(QDropHandler(self))
if __name__=="__main__":
app= QtWidgets.QApplication(sys.argv)
window=root_App()
window.show()
sys.exit(app.exec_())
和我的UI的XML:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>758</width>
<height>424</height>
</rect>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QLineEdit" name="lineEdit_1">
<property name="geometry">
<rect>
<x>40</x>
<y>140</y>
<width>691</width>
<height>20</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
我使用qurl ::路径()和qurl():: toLocalFile()。结果是一样的。但:: host()返回我想要的字符串:file:/// D:/ Qt。我无法理解,为什么路径()返回。 –