사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)


문제 설명

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Qt Designer에서 만든 사용자 정의 대화 상자를 사용할 수 없습니다. 대화 상자를 팝업할 수 있는 방법을 알고 있지만 해당 줄 텍스트에서 데이터를 가져올 수 없습니다.

main program.py

6
from PyQt5 import QtCore, QtGui, QtWidgets
from ui import Ui_MainWindow
from addui import Ui_Dialog as Form
from bs4 import BeautifulSoup
import requests
import time
import sys


class MainDialog(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.actionRefresh.triggered.connect(self.refresh_btn)
    self.actionAdd.triggered.connect(self.add_btn)
    self.actionRemove.triggered.connect(self.remove_btn)
    self.actionSettings.triggered.connect(self.settings_btn)
    self.actionAbout.triggered.connect(self.about_btn)
    self.actionExit.triggered.connect(self.exit_btn)

def open_dialog(self):
    dialog = QtWidgets.QDialog()
    dialog.ui = Form()
    dialog.ui.setupUi(dialog)
    dialog.exec_()
    dialog.show()

def refresh_btn(self):
    print('Refresh')
    self.getting_data()

def add_btn(self):
    print('Add')
    self.open_dialog()

def remove_btn(self):
    print('Remove')

def settings_btn(self):
    print('Settings')
    QtWidgets.QMessageBox.warning(self, 'Settings',
                                  'Work in progress.\n'
                                  '   Coming soon!')

def about_btn(self):
    print('About')
    QtWidgets.QMessageBox.about(self, 'About Checking Prices',
                                'Checking Prices ‑ Beta v1.0\n'
                                '\n'
                                'Copyright(c) 2015 ‑ Pifu Valentin')

def exit_btn(self):
    self.close()

def getting_data(self):
    links = ['link1',
             'link2',
             'link3'
             ]
    self.statusBar.showMessage('Getting data...')
    try:
        for nr, link in enumerate(links, start=1):
            cont = requests.get(link)
            soup = BeautifulSoup(cont.content, "html.parser")
            title = soup.title.text[:40]
            price = soup.find('span', {'itemprop': 'price'}).text
            linetxt = ('{}. {} >> ${}').format(nr, title, price)
            if nr == 1:
                self.linetxt1.setText(linetxt)
            elif nr == 2:
                self.linetxt2.setText(linetxt)
            elif nr == 3:
                self.linetxt3.setText(linetxt)
        self.statusBar.showMessage('Last updated ‑ '+time.strftime('%H:%M:%S'))
    except:
        self.statusBar.showMessage('Error getting data.')


def main():
     app = QtWidgets.QApplication(sys.argv)
     form = MainDialog()
     form.show()
     app.exec_()

if __name__ == '__main__':
     main()

addui.py (대화 상자)

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
def setupUi(self, Dialog):
    Dialog.setObjectName("Dialog")
    Dialog.resize(200, 71)
    Dialog.setMinimumSize(QtCore.QSize(200, 71))
    Dialog.setMaximumSize(QtCore.QSize(200, 71))
    Dialog.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap("Icons/Plus‑32.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    Dialog.setWindowIcon(icon)
    self.gridLayout = QtWidgets.QGridLayout(Dialog)
    self.gridLayout.setObjectName("gridLayout")
    self.text_link = QtWidgets.QLineEdit(Dialog)
    self.text_link.setObjectName("text_link")
    self.gridLayout.addWidget(self.text_link, 0, 0, 1, 2)
    self.add_link = QtWidgets.QPushButton(Dialog)
    self.add_link.setObjectName("add_link")
    self.gridLayout.addWidget(self.add_link, 1, 0, 1, 1)
    self.cancel_link = QtWidgets.QPushButton(Dialog)
    self.cancel_link.setObjectName("cancel_link")
    self.gridLayout.addWidget(self.cancel_link, 1, 1, 1, 1)
    self.retranslateUi(Dialog)
    self.cancel_link.clicked.connect(self.exit_dialog)
    self.add_link.clicked.connect(self.get_link)

def retranslateUi(self, Dialog):
    _translate = QtCore.QCoreApplication.translate
    Dialog.setWindowTitle(_translate("Dialog", "Add link"))
    self.add_link.setText(_translate("Dialog", "Add"))
    self.cancel_link.setText(_translate("Dialog", "Cancel"))

def get_link(self):
    print(self.text_link.text())
    x = self.text_link.text()
    return x

def exit_dialog(self):
    self.destroy()

이 프로그램에 문제가 있습니다.

  1. 취소를 클릭하여 대화 상자만 종료하면 메인 프로그램. (저는 self.close, self.hide로 시도했습니다...)

  2. line_text에 링크를 추가하고 해당 링크를 메인 프로그램으로 가져오고 싶지만, 추가를 클릭하여 대화 상자를 닫고 데이터를 기본 프로그램으로 전달합니다.

  3. 대화 상자를 호출하는 방법은 괜찮습니까?

     def open_dialog(self):
       dialog = QtWidgets.QDialog()
       dialog.ui = Form()
       dialog.ui.setupUi(dialog)
       dialog.exec_()
       dialog.show()
    

감사합니다. 내가 어떻게 이것을 할 수 있는지 이해가되지 않습니다. 누군가가 도울 수 있기를 바랍니다. 다시 한 번 감사드립니다.


참조 솔루션

방법 1:

You need to exec_() to do this and Here is a minimal version of your code which is fixed from PyQt4 import QtCore, QtGui import sys

class PopUpDLG(QtGui.QDialog):
    def __init__(self):
        super(PopUpDLG, self).__init__()
        self.setObjectName("self")
        self.resize(200, 71)
        self.setMinimumSize(QtCore.QSize(200, 71))
        self.setMaximumSize(QtCore.QSize(200, 71))
        self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Icons/Plus‑32.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.text_link = QtGui.QLineEdit(self)
        self.text_link.setObjectName("text_link")
        self.gridLayout.addWidget(self.text_link, 0, 0, 1, 2)
        self.add_link = QtGui.QPushButton(self)
        self.add_link.setObjectName("add_link")
        self.gridLayout.addWidget(self.add_link, 1, 0, 1, 1)
        self.cancel_link = QtGui.QPushButton(self)
        self.cancel_link.setObjectName("cancel_link")
        self.gridLayout.addWidget(self.cancel_link, 1, 1, 1, 1)
        self.retranslateUi(self)
        self.cancel_link.clicked.connect(self.reject)
        self.add_link.clicked.connect(self.get_link)
        self.retrunVal = None

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Add link"))
        self.add_link.setText(_translate("Dialog", "Add"))
        self.cancel_link.setText(_translate("Dialog", "Cancel"))

    def get_link(self):
        self.retrunVal = self.text_link.text()
        self.accept()

    def exec_(self):
        super(PopUpDLG, self).exec_()
        return self.retrunVal


class MainDialog(QtGui.QMainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        centralwidget = QtGui.QWidget(self)
        self.layout = QtGui.QHBoxLayout(centralwidget)
        self.button = QtGui.QPushButton("Open")
        self.valText = QtGui.QLabel("")
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.valText)
        self.setCentralWidget(centralwidget)
        self.button.clicked.connect(self.open_dialog)

    def open_dialog(self):
        dialog = PopUpDLG()
        value = dialog.exec_()
        if value:
            self.valText.setText(value)


def main():
     app = QtGui.QApplication(sys.argv)
     form = MainDialog()
     form.show()
     app.exec_()

if __name__ == '__main__':
     main()

(by Valentin PifuAchayan)

참조 문서

  1. Close and get data from a custom dialog PyQT5 (CC BY‑SA 2.5/3.0/4.0)

#Python #pyqt #qt






관련 질문

Python - 파일 이름에 특수 문자가 있는 파일의 이름을 바꿀 수 없습니다. (Python - Unable to rename a file with special characters in the file name)

구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)

기본 숫자를 10 ^ 9 이상으로 늘리면 코드가 작동하지 않습니다. (Code fails to work when i increase the base numbers to anything over 10 ^ 9)

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Enthought Canopy의 Python: csv 파일 조작 (Python in Enthought Canopy: manipulating csv files)

학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)

다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)

여러 함수의 변수를 다른 함수로 사용 (Use variables from multiple functions into another function)

리프 텐서의 값을 업데이트하는 적절한 방법은 무엇입니까(예: 경사하강법 업데이트 단계 중) (What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent))

Boto3: 조직 단위의 AMI에 시작 권한을 추가하려고 하면 ParamValidationError가 발생합니다. (Boto3: trying to add launch permission to AMI for an organizational unit raises ParamValidationError)







코멘트