2017-02-23 34 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,路徑始終以斜槓開始。 –