簡體   English   中英

在QFileDialog彈出窗口中按按鈕退出應用程序

[英]Pressing button in QFileDialog popup exits application

我從PyQt4過渡到PyQt5 我的應用程序(使用QtDesigner創建)具有一個復選框,該復選框啟用了“保存”按鈕,以防您要保存文件。 PyQt4 ,對話框將打開,我選擇我的文件,按OK,完成。 我對主應用程序的“確定”按鈕執行了一項檢查,如果路徑無效(例如,如果您在QFileDialog按下了cancel),則會提示錯誤。

使用PyQt5如果我以任何方式(確定,取消,X)關閉QFileDialog ,我的應用程序將完全退出。 我只想關閉QFileDialog而不關閉我的主窗口。 我該怎么做呢? 感謝您的時間和幫助。

這是我的代碼的相關部分:

self.path = self.ui.savepathButton.pressed.connect(lambda: self.file_save())

def file_save(self):
    path = QFileDialog.getSaveFileName(self, "Choose a path and filename", os.getcwd().replace("\\", "/") +
                                       "/test.stl", filter="Stereolithography Files (*.stl)")
    self.ui.savepath_label.setText(path) <------ NO ERROR WITHOUT THIS LINE

def OKButton_click(self):
    if os.path.isdir(os.path.split(self.ui.savepath_label.text())[0]) is False:
        # Warning if the filename is invalid.
        file_error = QMessageBox()
        file_error.setIcon(QMessageBox.Warning)
        file_error.setText("Invalid path or filename.")
        file_error.setInformativeText("Please choose a working path and filename.")             file_error.setWindowTitle("File name error")
        file_error.setStandardButtons(QMessageBox.Ok)
        file_error.exec_()
    else:
        self.accept()

編輯:

我知道錯誤所在的位置,但仍然無法解決。 我在代碼中標記了這一行。 為什么self.ui.savepath_label.setText(path)終止我的應用程序?

我終於發現了(非常小的)錯誤:

雖然PyQt4顯然會自動將路徑寫為string ,但PyQt5不會。

我變了

self.ui.savepath_label.setText(path)

進入

self.ui.savepath_label.setText(str(path))

現在一切都很好。

PyQt4提供兩種不同的API:

  • API v1對對象使用Qt類型,因此您必須將QString之類的內容傳遞給setText方法。
  • API v2而是使用python類型,並且Qt對象的方法會自動將這些python類型轉換為它們的Qt變體,因此您必須將python str傳遞給它們。

此頁面中提到有關PyQt4的內容。 PyQt5僅支持API版本2 (該頁面還提到了其他差異)。

還要注意,根據問題pyqt5-查找文檔PyQt5方法getSaveFileName實際上返回一對(filename, filter)因此它實際上等效於PyQt4的getSaveFileNameAndFilter方法,這意味着您可以簡單地使用:

self.ui.savepath_label.setText(path[0])

設置文字。 最小的完整示例:

from PyQt5.QtWidgets import  QFileDialog, QWidget, QApplication, QHBoxLayout, QPushButton


class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__(None)
        layout = QHBoxLayout()
        self.button = QPushButton('click')
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.button.clicked.connect(self.ask_filename)
    def ask_filename(self):
        fname = QFileDialog.getSaveFileName(self, 'title')
        print(fname)
        self.button.setText(fname[0])


app = QApplication([])
window = Window()
window.show()
app.exec_()

順便說一句,如果將fname[0]更改為fname並嘗試從終端啟動此應用程序,則會收到以下有用的錯誤消息:

Traceback (most recent call last):
  File "test_qt.py", line 15, in ask_filename
    self.button.setText(fname)
TypeError: QAbstractButton.setText(str): argument 1 has unexpected type 'tuple'

它告訴您getSaveFileName的返回類型是一個元組而不是str

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM