PyQt: connecting a button in a dialog

I am writing my first PyQt program, but I have a button problem. I have read another Q&A but I have not been able to solve it.

Basically I have a main window with a menu bar. Clicking on the "actionSelect" menu item opens a new SelectFiles dialog. It contains a "ChooseDirButton" button that should open the selection directory widget and change the text "ShowPath" linedit with the selected directory.

My code looks like this:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

import TeraGui

class MainWindow(QMainWindow, TeraGui.Ui_MainWindow):
    path = ""

    def __init__(self, parent=None):       
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.actionSelect.triggered.connect(self.Select)

    def Select(self):
        dialog = QDialog()
        dialog.ui = TeraGui.Ui_SelectFiles()
        dialog.ui.setupUi(dialog)
        dialog.setAttribute(Qt.WA_DeleteOnClose)
        dialog.exec_()

    def ChooseDirectory():
        global path
        path = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        self.ShowPath.setText(path)

app = QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()

      

I cannot resolve the ChooseDirectory method when the "ChooseDirButton" button is clicked. I tried to link them, but I don't understand the correct syntax. Moreover, there might be something wrong with the SelectDirectory method. I created a GUI with Qt Designer and imported it using the "import TeraGui" command.

+3


source to share


1 answer


It looks like you need to subclass your dialog, just like the main window.

I can't test it without your ui modules, but something like this should work:



from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

import TeraGui

class MainWindow(QMainWindow, TeraGui.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.actionSelect.triggered.connect(self.Select)

    def Select(self):
        dialog = Dialog(self)
        dialog.exec_()
        self.ShowPath.setText(dialog.path)

class Dialog(QDialog, TeraGui.Ui_SelectFiles):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi(self)
        self.ChooseDirButton.clicked.connect(self.ChooseDirectory)
        self.path = ''

    def ChooseDirectory(self):
        self.path = str(QFileDialog.getExistingDirectory(
            self, "Select Directory"))

app = QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()

      

+1


source







All Articles