python 多个QInputDialog

标签 python pyqt5

对于 PyQt5 仪器项目,我希望有几个相继的 QInputDialog 以便输入一些输入。 如果用户按下“取消”按钮,我希望程序返回到第一个对话框窗口。 这是我的代码:

def getChoice(self):

        while True:
            items = ("Make a new testfile","Open an existing one")
            item, okPressed = QInputDialog.getItem(self, "Select","You want to: ", items, 0, False)

            if not okPressed:      #close all
                sys.exit(0)

            elif okPressed and item:    
                print(item)
                if item == "Open an existing one" :
                    pathFile, ok = QFileDialog.getOpenFileName(self, "Open a file", "","All Files(*);;Python Files (*.py)")
                    print(pathFile)
                    break

                elif item == "Make a new testfile" :
                    items2 = ("New profil","Existing profil")
                    item2, okPressed2 = QInputDialog.getItem(self,"Select", "", items2, 0, False)

                    if not okPressed2:    #pass so come back to the previous inputDialog
                        pass

                    elif okPressed2 and item2:
                        print(item2)
                        if item2 == "New profil" :
                            while True:
                                name, ok = QInputDialog.getText(self, "Profil name", "Enter name:", QLineEdit.Normal)
                                if ok and name:
                                    dirName = 'Profiles/' + name
                                    if not os.path.exists(dirName):
                                        os.makedirs(dirName)
                                        break
                                    else :
                                        QMessageBox.about(self, 'Error','Profile name already taken')

                                elif ok and not name:
                                    QMessageBox.about(self, 'Error', 'Enter a name')

                                else :
                                    #here I'd like to return to the initial inputDialog if the user press cancel
                                    break


                        elif item2 == "Existing profil" :
                            pathprofil = QFileDialog.getOpenFileName(self, "Nom de profil", "","All Files(*)")
                            print(pathprofil)

                    break

使用这种方法,当第二个 while 循环发生时,我遇到了问题:我想在激活取消按钮时返回到第一个循环。

我不认为存在一种方法可以打破另一个 while 循环,而且我缺乏想象力..

关于如何做到这一点有什么想法吗?

最佳答案

尝试一下:

import os
from PyQt5.QtWidgets import (QApplication, QWidget, QLineEdit, 
                             QInputDialog, QFileDialog, QMessageBox,
                             QGridLayout, QLabel, QPushButton, QFrame)

class InputDialog(QWidget):
    def __init__(self):       
        super(InputDialog,self).__init__()

        label1 = QLabel("Make/Open file:")
        label2 = QLabel("pathFile:")
        label3 = QLabel("profil:")

        self.nameLable = QLabel()
        self.nameLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)      
        self.pathFile = QLabel()
        self.pathFile.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.profilLable = QLabel()
        self.profilLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)

        nameButton = QPushButton("...")
        nameButton.clicked.connect(self.selectName)
        profilButton = QPushButton("...")
        profilButton.clicked.connect(self.selectProfil)

        mainLayout = QGridLayout()
        mainLayout.addWidget(label1,          0, 0)
        mainLayout.addWidget(self.nameLable,  0, 1)
        mainLayout.addWidget(nameButton,      0, 2)
        mainLayout.addWidget(label3,          1, 0)
        mainLayout.addWidget(self.profilLable,1, 1)
        mainLayout.addWidget(profilButton,    1, 2)
        mainLayout.addWidget(label2,          2, 0)
        mainLayout.addWidget(self.pathFile,   2, 1, 1, 2)
        mainLayout.setRowMinimumHeight(2, 40)        
        mainLayout.addWidget(QLabel(), 3, 0)        
        mainLayout.setRowStretch(3, 1)
        mainLayout.setColumnMinimumWidth(1, 200 )
        mainLayout.setSpacing(5)

        self.setLayout(mainLayout)

    def selectName(self):
        items = ("Make a new testfile", "Open an existing one")
        item, okPressed = QInputDialog.getItem(self, 
                                    "Select",
                                    "You want to: ", 
                                    items, 0, False)
        if okPressed :
            self.nameLable.setText(item)  
            if item == "Open an existing one" :
                pathFile, ok = QFileDialog.getOpenFileName(self, 
                                    "Open a file", 
                                    "",
                                    "All Files(*);;Python Files (*.py)")
                if pathFile: 
                    self.pathFile.setText(pathFile)
                    self.profilLable.setText("")
            elif item == "Make a new testfile" :
                self.selectProfil()
        else:
            sys.exit(0)

    def selectProfil(self):
        if self.nameLable.text() == "Make a new testfile" :
            self.pathFile.setText("")
            items2 = ("New profil", "Existing profil")
            item2, okPressed2 = QInputDialog.getItem(self,"Select", "", items2, 0, False)
            if not okPressed2:      #pass so come back to the previous inputDialog
                 self.selectName()   
            self.profilLable.setText(item2)
            if item2 == "New profil" :
                name, ok = QInputDialog.getText(self, 
                                     "Profil name", 
                                     "Enter file name:", 
                                     QLineEdit.Normal)
                if ok and name:
                    dirName = 'Profiles'                    #  /' + name
                    if not os.path.exists(dirName):
                        os.makedirs(dirName)

                    filepath = os.path.join(dirName, name)
                    if not os.path.isfile(filepath):                    
                        f = open(filepath, "a")
                        f.close()
                        self.pathFile.setText(os.path.abspath(filepath))
                    else :
                        QMessageBox.about(self, 'Error','Profile name already taken')
                        self.selectProfil()
                elif ok and not name:
                    QMessageBox.about(self, 'Error', 'Enter a name')

                else :
                    #here I'd like to return to the initial inputDialog if the user press cancel
                    self.selectProfil()
            elif item2 == "Existing profil" :
                pathprofil, ok = QFileDialog.getOpenFileName(self, 
                                             "Nom de profil", 
                                             "", "All Files(*)")
                self.pathFile.setText(pathprofil) 
        elif not self.nameLable.text():        
            QMessageBox.about(self, 'Error', 'Select `Make / Open file`')
            self.selectName()

if __name__=="__main__":
    import sys
    app    = QApplication(sys.argv)
    myshow = InputDialog()
    myshow.setWindowTitle("InputDialog")
    myshow.show()
    sys.exit(app.exec_())

enter image description here

关于python 多个QInputDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004880/

相关文章:

Python Numpy 平方均值计算(这是正确的方法吗)

Python 子进程 readline() 挂起;不能使用普通选项

python - 如何从 PyQt5 中的 QWidget 内部使用 statusBar().showMessage() ?

python - QGraphicsPathItem .setPen() 影响文本样式

python - Mayavi:自定义工具栏

python - 从 PyQT5 检索 QtTableWidget 单元格的内容

python - 每个 Django 应用程序的不同 virtualenv

python: os.system不执行shell命令

python - 是否可以在 Folium map 中绘制带箭头的线条?

Python/PYQT5-隐藏菜单时崩溃,如果从主窗口运行