Issue
As I read in the documentation you can not return anythong from slots in pyqt, so then I decided to emit a signal from my slot but the problem is the signal is an object but I need the string of that object to put it to use. first, Am I right about the returning in pyqt slots? Second, How can I extract the string from signal object? third, is there another to that?
import sys
from PyQt6.QtCore import pyqtSignal, pyqtSlot
from PyQt6.QtWidgets import QWidget, QFileDialog, QPushButton, QVBoxLayout, QApplication
#initializing QApplication
app = QApplication(sys.argv)
class Window(QWidget):
directory = pyqtSignal(str)
def __init__(self) -> None:
super().__init__()
self.unrealEditorBtn = QPushButton("UnrealEditor Directory")
#fileDialog or selecting UnrealEditor
self.editorFileDialog = QFileDialog()
self.editorFileDialog.setFileMode(QFileDialog.FileMode.Directory)
#layout
vLayout = QVBoxLayout()
self.setLayout(vLayout)
#editor button signal
self.unrealEditorBtn.clicked.connect(self.openingFileDialog_forEditor)
#method for getting the directory of UnrealEditor.exe
@pyqtSlot(result=str)
def openingFileDialog_forEditor(self):
#this line gets the directory and put it inside self.directoy signal
self.directory.emit(str(self.editorFileDialog.getExistingDirectory(self , "PLease select the UnrealEditor.exe Directory")))
w = Window()
w.show()
sys.exit(app.exec())
As you can see in my code I want to get the existing directory to the directory class attribute then extract the string from that. Maybe I'm completely wrong or there's another way to do that.
Solution
As pointed out in the comment, getExistingDirectory()
is static so you're not using it correctly.
Here's a working example of how you could use the path you get from the file dialog.
Selecting the dir sets it as an instance variable which can then be used for whatever you want.
import sys
from PyQt6.QtWidgets import QWidget, QFileDialog, QPushButton, QVBoxLayout, QApplication
class Window(QWidget):
def __init__(self) -> None:
super().__init__()
self.unreal_dir = None
self.unrealEditorBtn = QPushButton("UnrealEditor Directory")
self.use_unreal_dir = QPushButton("use unreal dir")
v_layout = QVBoxLayout(self)
v_layout.addWidget(self.unrealEditorBtn)
v_layout.addWidget(self.use_unreal_dir)
self.unrealEditorBtn.clicked.connect(self.select_unreal_dir)
self.use_unreal_dir.clicked.connect(self.do_something_with_unreal_dir)
def select_unreal_dir(self):
selected = QFileDialog.getExistingDirectory(self, "PLease select the UnrealEditor.exe Directory")
if not selected:
return
self.unreal_dir = selected
def do_something_with_unreal_dir(self):
if not self.unreal_dir:
print('select dir first')
return
# replace print below with whatever you want with the path
print(self.unreal_dir)
app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec())
Answered By - mahkitah
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.