天天看點

python pyqt5 彈出框傳遞資料-- coding: utf-8 ---- coding: utf-8 --

-- coding: utf-8 --

'''

【簡介】

對話框關閉時傳回值給主視窗 例子           

複制

'''

from PyQt5.QtCore import *

from PyQt5.QtGui import *

from PyQt5.QtWidgets import *

import sys

class DateDialog(QDialog):

def init(self, parent=None):

super(DateDialog, self).init(parent)

self.setWindowTitle('DateDialog')

# 在布局中添加部件
    layout = QVBoxLayout(self)
    self.datetime = QDateTimeEdit(self)
    self.datetime.setCalendarPopup(True)
    self.datetime.setDateTime(QDateTime.currentDateTime())
    layout.addWidget(self.datetime)

    # 使用兩個button(ok和cancel)分别連接配接accept()和reject()槽函數
    buttons = QDialogButtonBox(
        QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
        Qt.Horizontal, self)
    buttons.accepted.connect(self.accept)
    buttons.rejected.connect(self.reject)
    layout.addWidget(buttons)

# 從對話框中擷取目前日期和時間
def dateTime(self):
    return self.datetime.dateTime()

# 靜态方法建立對話框并傳回 (date, time, accepted)
@staticmethod
def getDateTime(parent=None):
    dialog = DateDialog(parent)
    result = dialog.exec_()
    date = dialog.dateTime()
    return (date.date(), date.time(), result == QDialog.Accepted)           

複制

-- coding: utf-8 --

'''

【簡介】

對話框關閉時傳回值給主視窗例子

'''

class WinForm(QWidget):

def init(self, parent=None):

super(WinForm, self).init(parent)

self.resize(400, 90)

self.setWindowTitle('對話框關閉時傳回值給主視窗例子')

self.lineEdit = QLineEdit(self)
    self.button1 = QPushButton('彈出對話框1')
    self.button1.clicked.connect(self.onButton1Click)

    self.button2 = QPushButton('彈出對話框2')
    self.button2.clicked.connect(self.onButton2Click)

    gridLayout = QGridLayout()
    gridLayout.addWidget(self.lineEdit)
    gridLayout.addWidget(self.button1)
    gridLayout.addWidget(self.button2)
    self.setLayout(gridLayout)

def onButton1Click(self):
    dialog = DateDialog(self)
    result = dialog.exec_()
    date = dialog.dateTime()
    self.lineEdit.setText(date.date().toString())
    print('\n日期對話框的傳回值')
    print('date=%s' % str(date.date()))
    print('time=%s' % str(date.time()))
    print('result=%s' % result)
    dialog.destroy()

def onButton2Click(self):
    date, time, result = DateDialog.getDateTime()
    self.lineEdit.setText(date.toString())
    print('\n日期對話框的傳回值')
    print('date=%s' % str(date))
    print('time=%s' % str(time))
    print('result=%s' % result)
    if result == QDialog.Accepted:
        print('點選确認按鈕')
    else:
        print('點選取消按鈕')           

複制

if name == "main":

app = QApplication(sys.argv)

form = WinForm()

form.show()

sys.exit(app.exec_())