简体   繁体   English

如何在 QDialog 中访问 QLineEdit?

[英]How to access QLineEdit in QDialog?

I created a custom dialog that contains a QLineEdit.我创建了一个包含 QLineEdit 的自定义对话框。 When certain criteria matches on the main screen, the dialog opens up and allows the user to enter input.当某些标准在主屏幕上匹配时,对话框打开并允许用户输入输入。 Upon returning the the main screen, that input needs to be grabbed and used.返回主屏幕后,需要抓取并使用该输入。

In QtDesigner, I created I dialog (with the Ok and Cancel buttons already on it) and added a QLineEdit with an object name of lineEdit.在 QtDesigner 中,我创建了 I 对话框(上面已经有 Ok 和 Cancel 按钮)并添加了一个 QLineEdit,其名称为 lineEdit 的 object。

also I'm using three.py file one is main_app which is importing other two files mainwindow file and dialog file (converted from.ui file) following is the method I'm using to open dialog in my main_app file.我也在使用三个.py 文件,一个是 main_app,它正在导入其他两个文件 mainwindow 文件和对话框文件(从.ui 文件转换)以下是我用来在我的 main_app 文件中打开对话框的方法。

def open_dialog(self):
    Dialog = QtWidgets.QDialog()
    ui = sub_search.Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    resp = Dialog.exec_()

    if resp == QtWidgets.QDialog.Accepted:
        print("Accepted!")           #this place will be used to do something more once I have 
                                      #userinupt from dialog box

till this end code is working fine I'm not sure how to return and use user input following is the code I'm trying to return input of lineEdit from dialog box直到这个结束代码工作正常我不确定如何返回和使用用户输入以下是我试图从对话框返回 lineEdit 输入的代码

    def get_text_from(self):
    if self.lineEdit.text() != "" and self.buttonBox.accepted():
        swc = self.lineEdit.text()
        return swc
    elif self.lineEdit.text() == "" and self.buttonBox.accepted():
        warning_message(title="Warning!", message="please provide swc clli,thanks!")
    else:
        pass

following are the complete code where I want to put more filter based on user input main_app.py以下是我想根据用户输入 main_app.py 放置更多过滤器的完整代码

from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMessageBox
import pandas as pd
from pyqt_master_data import search, sub_search

pd.set_option('display.max_rows', None, 'display.max_columns', None)

master_data = pd.read_excel('Master_data.xlsx', 'Shares')

class SearchTool(search.Ui_main, QtWidgets.QMainWindow):

    def __init__(self):
        super(SearchTool, self).__init__()
        self.setupUi(self)
        self.push()

    def master_data_search(self):
        if self.lineEdit.text() != "":
            day = self.lineEdit.text().strip()
            if day.upper() in "TUESDAY":
               self.open_dialog()
            else:
               day_df = master_data[(master_data.Day.str.contains(day, 
case=False, na=False))]
                model = PandasModel(day_df)
                self.tableView.setModel(model)

    def push(self):
        self.pushButton.clicked.connect(self.master_data_search)

    def open_dialog(self):
        Dialog = QtWidgets.QDialog()
        ui = sub_search.Ui_Dialog()
        ui.setupUi(Dialog)
        Dialog.show()
        resp = Dialog.exec_()

        if resp == QtWidgets.QDialog.Accepted:
            print("Accepted!")
            sub_search.Ui_Dialog.get_text_from() #do something here
        else:
           print('rejected')


def warning_message(title="Warning!", message="Please provide input, 
thanks!"):
    QMessageBox.information(None, title, message)


class PandasModel(QtCore.QAbstractTableModel):
    """
    Class to populate a table view with a pandas dataframe
    """
    def __init__(self, data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._data = data

    def rowCount(self, parent=None):
        return len(self._data.values)

    def columnCount(self, parent=None):
        return self._data.columns.size

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if role == QtCore.Qt.DisplayRole:
                return str(self._data.values[index.row()][index.column()])
        return None

    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == 
QtCore.Qt.DisplayRole:
            return self._data.columns[col]
        return None


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    qt_app = SearchTool()
    qt_app.show()
    app.exec_()

search.py搜索.py

from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_main(object):
def setupUi(self, main):
    main.setObjectName("main")
    main.resize(855, 886)
    main.setMouseTracking(True)
    main.setTabletTracking(True)
    self.centralwidget = QtWidgets.QWidget(main)
    self.centralwidget.setObjectName("centralwidget")
    self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)
    self.verticalLayout_2.setObjectName("verticalLayout_2")
    self.frame = QtWidgets.QFrame(self.centralwidget)
    self.frame.setFrameShape(QtWidgets.QFrame.Box)
    self.frame.setFrameShadow(QtWidgets.QFrame.Plain)
    self.frame.setObjectName("frame")
    self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
    self.verticalLayout.setObjectName("verticalLayout")
    self.label = QtWidgets.QLabel(self.frame)
    self.label.setAlignment(QtCore.Qt.AlignCenter)
    self.label.setObjectName("label")
    self.verticalLayout.addWidget(self.label)
    self.lineEdit = QtWidgets.QLineEdit(self.frame)
    self.lineEdit.setClearButtonEnabled(True)
    self.lineEdit.setObjectName("lineEdit")
    self.verticalLayout.addWidget(self.lineEdit)
    self.pushButton = QtWidgets.QPushButton(self.frame)
    font = QtGui.QFont()
    font.setBold(True)
    font.setItalic(True)
    font.setWeight(75)
    self.pushButton.setFont(font)
    self.pushButton.setObjectName("pushButton")
    self.verticalLayout.addWidget(self.pushButton)
    self.verticalLayout_2.addWidget(self.frame)
    self.frame_2 = QtWidgets.QFrame(self.centralwidget)
    self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
    self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
    self.frame_2.setObjectName("frame_2")
    self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_2)
    self.verticalLayout_3.setObjectName("verticalLayout_3")
    self.frame_3 = QtWidgets.QFrame(self.frame_2)
    self.frame_3.setMouseTracking(True)
    self.frame_3.setTabletTracking(True)
    self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
    self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
    self.frame_3.setObjectName("frame_3")
    self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_3)
    self.verticalLayout_4.setObjectName("verticalLayout_4")
    self.tableView = QtWidgets.QTableView(self.frame_3)
    self.tableView.setMouseTracking(True)
    self.tableView.setTabletTracking(True)
    self.tableView.setFrameShape(QtWidgets.QFrame.StyledPanel)
    self.tableView.setFrameShadow(QtWidgets.QFrame.Plain)
    self.tableView.setDragEnabled(True)
    self.tableView.setDefaultDropAction(QtCore.Qt.CopyAction)
    self.tableView.setSortingEnabled(True)
    self.tableView.setObjectName("tableView")
    self.verticalLayout_4.addWidget(self.tableView)
    self.verticalLayout_3.addWidget(self.frame_3)
    self.verticalLayout_2.addWidget(self.frame_2)
    main.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(main)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 855, 26))
    self.menubar.setObjectName("menubar")
    main.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(main)
    self.statusbar.setObjectName("statusbar")
    main.setStatusBar(self.statusbar)

    self.retranslateUi(main)
    QtCore.QMetaObject.connectSlotsByName(main)

def retranslateUi(self, main):
    _translate = QtCore.QCoreApplication.translate
    main.setWindowTitle(_translate("main", "MainWindow"))
    self.label.setText(_translate("main", "DATA"))
    self.lineEdit.setPlaceholderText(_translate("main", "day"))
    self.pushButton.setText(_translate("main", "SEARCH"))

sub_search.py sub_search.py

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox
class Ui_Dialog(object):
def setupUi(self, Dialog):
    Dialog.setObjectName("Dialog")
    Dialog.resize(478, 170)
    Dialog.setMaximumSize(QtCore.QSize(560, 170))
    self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog)
    self.verticalLayout_2.setObjectName("verticalLayout_2")
    self.frame = QtWidgets.QFrame(Dialog)
    self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
    self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
    self.frame.setObjectName("frame")
    self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
    self.verticalLayout.setObjectName("verticalLayout")
    self.label = QtWidgets.QLabel(self.frame)
    self.label.setAlignment(QtCore.Qt.AlignCenter)
    self.label.setObjectName("label")
    self.verticalLayout.addWidget(self.label)
    self.lineEdit = QtWidgets.QLineEdit(self.frame)
    self.lineEdit.setObjectName("lineEdit")
    self.verticalLayout.addWidget(self.lineEdit)
    self.verticalLayout_2.addWidget(self.frame)
    self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
    self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
    self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
    self.buttonBox.setCenterButtons(True)
    self.buttonBox.setObjectName("buttonBox")
    self.verticalLayout_2.addWidget(self.buttonBox)

    self.retranslateUi(Dialog)
    self.buttonBox.accepted.connect(Dialog.accept)
    self.buttonBox.rejected.connect(Dialog.reject)
    QtCore.QMetaObject.connectSlotsByName(Dialog)


def get_text_from(self):
    if self.lineEdit.text() != "" and self.buttonBox.accepted():
        swc = self.lineEdit.text()
        return swc
    elif self.lineEdit.text() == "" and self.buttonBox.accepted():
        warning_message(title="Warning!", message="please provide swc clli,thanks!")
    else:
        pass

def retranslateUi(self, Dialog):
    _translate = QtCore.QCoreApplication.translate
    Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
    self.label.setText(_translate("Dialog", "TextLabel"))
    self.buttonBox.accepted.connect(self.get_text_from)


def warning_message(title="Warning!", message="Please provide input, 
thanks!"):
    QMessageBox.information(None, title, message)



if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

my Questions are how do capture lineEdit value and use in my main_app file.我的问题是如何捕获 lineEdit 值并在我的 main_app 文件中使用。 I realize I've still got lots to learn so if someone could point in the right direction that would be awesome.我意识到我还有很多东西要学,所以如果有人能指出正确的方向,那就太棒了。 I got decent start but I'm not sure how to finish this..我有一个不错的开始,但我不知道如何完成这个..

thanks in advance!提前致谢!

You could try something like this:你可以尝试这样的事情:

class SearchTool(search.Ui_main, QtWidgets.QMainWindow):

    def __init__(self):
        super(SearchTool, self).__init__()
        self.setupUi(self)
        self.push()

    def master_data_search(self):
        if self.lineEdit.text() != "":
            day = self.lineEdit.text().strip()
            if day.upper() in "TUESDAY":
                result = self.open_dialog()
                if result is not None:
                    print(f'the search result was {result}')
                else:
                    print('the search was canceled')
            else:
                print('do something else')

    def push(self):
        self.pushButton.clicked.connect(self.master_data_search)

    def open_dialog(self):
        print('open dialog')
        Dialog = QtWidgets.QDialog(self)
        ui = sub_search.Ui_Dialog()
        ui.setupUi(Dialog)
        #Dialog.show()
        resp = Dialog.exec_()

        if resp == QtWidgets.QDialog.Accepted:
            print("Accepted!")
            # retrieve text from line edit in dialog and return it
            return ui.lineEdit.text()
        else:
            print('rejected')
            return None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM