2017-02-23 35 views
3

我用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> 
+0

我使用qurl ::路径()和qurl():: toLocalFile()。结果是一样的。但:: host()返回我想要的字符串:file:/// D:/ Qt。我无法理解,为什么路径()返回。 –

回答

0

QLineEdit类已经支持拖放网址。您的自定义处理程序没有完全覆盖该处理程序,因此这解释了文本输入两次的原因。为了完全覆盖默认行为,你的事件过滤器必须返回True - 意思是说,我已经处理了这个事件,所以没有什么可做的了。

你的示例代码可被简化为这样:

class root_App(QtWidgets.QMainWindow, Ui_MainWindow): 
    def __init__(self): 
     super(root_App, self).__init__() 
     self.setupUi(self) 
     self.lineEdit_1.installEventFilter(self) 

    def eventFilter(self, source, event): 
     if (event.type() == QEvent.Drop and 
      source is self.lineEdit_1): 
      md = event.mimeData() 
      if md.hasUrls(): 
       source.setText(md.urls()[0].path()) 
       return True 
     return super(root_App, self).eventFilter(source, event) 
+0

它的工作原理,我将它应用到一般的“处理程序”而不是指定的。谢谢!但是“path()”返回一个没有file://的url。这意味着结果是/ D:/ xyz。由于url包含主机和路径,本地文件的“主机”是“file://”? –

+0

忘记评论...根据RFC2396,路径始终以斜杠开始。 –