PyQt – Load data from .txt file via Drag and Drop
Hello everyone!
I have a folder TreeView on the left layout and I want to drag a .txt file from there and drop it to the other layout. Hopefully, I want to load the data of that dropped file on a variable.
For the code’s needs, I used till now (to my “real†code) the np.loadtxt() to load the data, so I’d like to use it here too.
In case it matters, the .txt file contains 4 columns (coordinates).
I post my code. The program closes when I drop the file.
Thanks in advance!
Code:
import sys, time, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import numpy as np
import pylab as pl
import random
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setCentralWidget(self.central_widget)
self.
pathRoot = QDir.
rootPath()
self.dirmodel = QFileSystemModel(self)
self.
dirmodel.
setRootPath(QDir.
currentPath())
self.indexRoot = self.dirmodel.index(self.dirmodel.rootPath())
self.folder_view.setDragEnabled(True)
self.folder_view.setModel(self.dirmodel)
self.folder_view.setRootIndex(self.indexRoot)
self.selectionModel = self.folder_view.selectionModel()
self.left_layout.addWidget(self.folder_view)
self.folderLayout.setLayout(self.left_layout)
splitter_filebrowser
= QSplitter(Qt.
Horizontal) splitter_filebrowser.addWidget(self.folderLayout)
splitter_filebrowser.addWidget(Figure_Canvas(self))
splitter_filebrowser.setStretchFactor(1, 1)
hbox.addWidget(splitter_filebrowser)
self.centralWidget().setLayout(hbox)
self.setWindowTitle('Simple drag & drop')
self.setGeometry(750, 100, 600, 500)
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
self.right_layout.addWidget(blabla)
self.buttonLayout.setLayout(self.right_layout)
def dragEnterEvent(self, e):
if e.mimeData().hasFormat('text/uri-list'):
e.accept()
else:
e.ignore()
def dropEvent(self, e):
print("something")
data = np.loadtxt(e.mimeData())
print(data)
if __name__ == '__main__':
ex = Example()
ex.show()
app.exec_()
Re: PyQt – Load data from .txt file via Drag and Drop
Can "np.loadtxt" handle a QMimeData object as its argument?
Cheers,
_
Re: PyQt – Load data from .txt file via Drag and Drop
Hi anda_skoa, thanks for your quick reply!
Truth is I have no idea, but I’m checking it out now in case I find something and I’ll post.
Have you any clue if it could be done in another way? For example to get the file name (e.g. this_file.txt) and then use something like:
Code:
with open("test_5.txt") as f:
data2 = np.loadtxt("this_file.txt ")
Thanks again!