• Pyqt 窗体间传值


    窗体间传值网上有好多方法,比如新建文件,先将子类窗体的数据传到文件中,父窗体读取文件、  Signal&Slot机制进行传值 等等

    在这里,我们就举个采用apply方法:Signal&Slot的例子

    不必多说,三个文件搞定一切!

    parent.ui:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <ui version="4.0">
     3  <class>MainWindow</class>
     4  <widget class="QMainWindow" name="MainWindow">
     5   <property name="geometry">
     6    <rect>
     7     <x>0</x>
     8     <y>0</y>
     9     <width>339</width>
    10     <height>201</height>
    11    </rect>
    12   </property>
    13   <property name="windowTitle">
    14    <string>MainWindow</string>
    15   </property>
    16   <widget class="QWidget" name="centralwidget">
    17    <widget class="QPushButton" name="BtnOpenC">
    18     <property name="geometry">
    19      <rect>
    20       <x>250</x>
    21       <y>150</y>
    22       <width>75</width>
    23       <height>23</height>
    24      </rect>
    25     </property>
    26     <property name="text">
    27      <string>子窗体</string>
    28     </property>
    29    </widget>
    30    <widget class="QTextEdit" name="textEdit">
    31     <property name="geometry">
    32      <rect>
    33       <x>20</x>
    34       <y>20</y>
    35       <width>301</width>
    36       <height>91</height>
    37      </rect>
    38     </property>
    39    </widget>
    40   </widget>
    41  </widget>
    42  <resources/>
    43  <connections/>
    44 </ui>

    child.ui:

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>Dialog</class>
     <widget class="QDialog" name="Dialog">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>339</width>
        <height>182</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>Dialog</string>
      </property>
      <widget class="QLineEdit" name="lineEdit">
       <property name="geometry">
        <rect>
         <x>100</x>
         <y>50</y>
         <width>221</width>
         <height>20</height>
        </rect>
       </property>
      </widget>
      <widget class="QLabel" name="label">
       <property name="geometry">
        <rect>
         <x>20</x>
         <y>50</y>
         <width>54</width>
         <height>21</height>
        </rect>
       </property>
       <property name="text">
        <string>Data:</string>
       </property>
      </widget>
      <widget class="QPushButton" name="pushButtonOK">
       <property name="geometry">
        <rect>
         <x>150</x>
         <y>140</y>
         <width>75</width>
         <height>23</height>
        </rect>
       </property>
       <property name="text">
        <string>Ok</string>
       </property>
      </widget>
      <widget class="QPushButton" name="pushButtonCancel">
       <property name="geometry">
        <rect>
         <x>240</x>
         <y>140</y>
         <width>75</width>
         <height>23</height>
        </rect>
       </property>
       <property name="text">
        <string>Cancel</string>
       </property>
      </widget>
     </widget>
     <resources/>
     <connections/>
    </ui>

    分别转换为py

    parent.py:

     1 # -*- coding: utf-8 -*-
     2 
     3 # Form implementation generated from reading ui file 'parent.ui'
     4 #
     5 # Created: Wed Mar 25 16:14:25 2015
     6 #      by: PyQt4 UI code generator 4.10.3
     7 #
     8 # WARNING! All changes made in this file will be lost!
     9 
    10 from PyQt4 import QtCore, QtGui
    11 
    12 try:
    13     _fromUtf8 = QtCore.QString.fromUtf8
    14 except AttributeError:
    15     def _fromUtf8(s):
    16         return s
    17 
    18 try:
    19     _encoding = QtGui.QApplication.UnicodeUTF8
    20     def _translate(context, text, disambig):
    21         return QtGui.QApplication.translate(context, text, disambig, _encoding)
    22 except AttributeError:
    23     def _translate(context, text, disambig):
    24         return QtGui.QApplication.translate(context, text, disambig)
    25 
    26 class Ui_MainWindow(object):
    27     def setupUi(self, MainWindow):
    28         MainWindow.setObjectName(_fromUtf8("MainWindow"))
    29         MainWindow.resize(339, 201)
    30         self.centralwidget = QtGui.QWidget(MainWindow)
    31         self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
    32         self.BtnOpenC = QtGui.QPushButton(self.centralwidget)
    33         self.BtnOpenC.setGeometry(QtCore.QRect(250, 150, 75, 23))
    34         self.BtnOpenC.setObjectName(_fromUtf8("BtnOpenC"))
    35         self.textEdit = QtGui.QTextEdit(self.centralwidget)
    36         self.textEdit.setGeometry(QtCore.QRect(20, 20, 301, 91))
    37         self.textEdit.setObjectName(_fromUtf8("textEdit"))
    38         MainWindow.setCentralWidget(self.centralwidget)
    39 
    40         self.retranslateUi(MainWindow)
    41         QtCore.QMetaObject.connectSlotsByName(MainWindow)
    42 
    43     def retranslateUi(self, MainWindow):
    44         MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
    45         self.BtnOpenC.setText(_translate("MainWindow", "子窗体", None))
    46 
    47 
    48 if __name__ == "__main__":
    49     import sys
    50     app = QtGui.QApplication(sys.argv)
    51     MainWindow = QtGui.QMainWindow()
    52     ui = Ui_MainWindow()
    53     ui.setupUi(MainWindow)
    54     MainWindow.show()
    55     sys.exit(app.exec_())

    child.py:

     1 # -*- coding: utf-8 -*-
     2 
     3 # Form implementation generated from reading ui file 'child.ui'
     4 #
     5 # Created: Wed Mar 25 16:14:29 2015
     6 #      by: PyQt4 UI code generator 4.10.3
     7 #
     8 # WARNING! All changes made in this file will be lost!
     9 
    10 from PyQt4 import QtCore, QtGui
    11 
    12 try:
    13     _fromUtf8 = QtCore.QString.fromUtf8
    14 except AttributeError:
    15     def _fromUtf8(s):
    16         return s
    17 
    18 try:
    19     _encoding = QtGui.QApplication.UnicodeUTF8
    20     def _translate(context, text, disambig):
    21         return QtGui.QApplication.translate(context, text, disambig, _encoding)
    22 except AttributeError:
    23     def _translate(context, text, disambig):
    24         return QtGui.QApplication.translate(context, text, disambig)
    25 
    26 class Ui_Dialog(object):
    27     def setupUi(self, Dialog):
    28         Dialog.setObjectName(_fromUtf8("Dialog"))
    29         Dialog.resize(339, 182)
    30         self.lineEdit = QtGui.QLineEdit(Dialog)
    31         self.lineEdit.setGeometry(QtCore.QRect(100, 50, 221, 20))
    32         self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
    33         self.label = QtGui.QLabel(Dialog)
    34         self.label.setGeometry(QtCore.QRect(20, 50, 54, 21))
    35         self.label.setObjectName(_fromUtf8("label"))
    36         self.pushButtonOK = QtGui.QPushButton(Dialog)
    37         self.pushButtonOK.setGeometry(QtCore.QRect(150, 140, 75, 23))
    38         self.pushButtonOK.setObjectName(_fromUtf8("pushButtonOK"))
    39         self.pushButtonCancel = QtGui.QPushButton(Dialog)
    40         self.pushButtonCancel.setGeometry(QtCore.QRect(240, 140, 75, 23))
    41         self.pushButtonCancel.setObjectName(_fromUtf8("pushButtonCancel"))
    42 
    43         self.retranslateUi(Dialog)
    44         QtCore.QMetaObject.connectSlotsByName(Dialog)
    45 
    46     def retranslateUi(self, Dialog):
    47         Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
    48         self.label.setText(_translate("Dialog", "Data:", None))
    49         self.pushButtonOK.setText(_translate("Dialog", "Ok", None))
    50         self.pushButtonCancel.setText(_translate("Dialog", "Cancel", None))
    51 
    52 
    53 if __name__ == "__main__":
    54     import sys
    55     app = QtGui.QApplication(sys.argv)
    56     Dialog = QtGui.QDialog()
    57     ui = Ui_Dialog()
    58     ui.setupUi(Dialog)
    59     Dialog.show()
    60     sys.exit(app.exec_())

    新建MainPvalue.py 文件,代码如下:

     1 # -*- coding: UTF8 -*-
     2 
     3 from PyQt4 import QtCore, QtGui
     4 from parent import Ui_MainWindow
     5 from child import Ui_Dialog
     6 import sys
     7 from PyQt4.QtGui import *
     8 
     9 class MainClass(QtGui.QMainWindow):
    10     def __init__(self, parent=None):
    11         super(MainClass, self).__init__(parent)
    12         self.Ui = Ui_MainWindow()
    13         self.Ui.setupUi(self)
    14         self.setFixedSize(self.width(), self.height())
    15 
    16 
    17         self.Ui.BtnOpenC.clicked.connect(self.Child)
    18 
    19     # 打开子窗体
    20     def Child(self):
    21         self.WChild = Ui_Dialog()
    22         self.Dialog = QtGui.QDialog(self)  # 不加self 不在父窗体中, 有两个任务栏 。 加self 表示在父子在窗体中在一个任务栏
    23 
    24         self.WChild.setupUi(self.Dialog)
    25 
    26         self.WChild.pushButtonOK.clicked.connect(self.GetLine)
    27         self.WChild.pushButtonCancel.clicked.connect(self.APPclose)
    28         self.Dialog.exec_()
    29     # 获取 弹框中填写的数据
    30     def GetLine(self):
    31         LineData=self.WChild.lineEdit.text()
    32         self.Ui.textEdit.setText(LineData)
    33         self.Dialog.close()
    34     # 关闭当前弹框
    35     def APPclose(self):
    36         self.Dialog.close()
    37 
    38 
    39 
    40 if __name__ == '__main__':
    41     app = QtGui.QApplication(sys.argv)
    42     MainApp = MainClass()
    43     MainApp.show()
    44     sys.exit(app.exec_())

    运行MainPvalue.py


    在父窗口定义一个子窗口的接口

    self.child=None
    然后实例子窗口赋给self.child 传递一个callback 函数

    class MainForm(QDialog):
        def __init__(self, parent=None):
            super(MainForm, self).__init__(parent)
            self.child = None
            self.table = QTableWidget()
            self.table.setColumnCount(40)
            self.table.setRowCount(30)
            # set Column tab title
            #self.table.setHorizontalHeaderLabels(list(range(5,10)))
            for i in range(0, 5):
                for x in range(0, 7):
                    item = QTableWidgetItem(str(i + x))
                    item.setTextAlignment(Qt.AlignLeft | Qt.AlignCenter)
                    item.setBackgroundColor(Qt.green)
                    self.table.setItem(x, i, item)
    
            lbutton = QPushButton("&L")
            Vlayout = QHBoxLayout()
            Vlayout.addWidget(lbutton)
            Hlayout = QVBoxLayout()
            Hlayout.addWidget(self.table)
            Hlayout.addLayout(Vlayout)
            self.setLayout(Hlayout)
            self.resize(400,300)
            self.setWindowTitle("Table")
            self.connect(lbutton, SIGNAL("clicked()"), self.liveChange)
    
        def callback(self, c=0, r=0):
            print('c=' + str(c) + 'r=' + str(r))
            self.table.clear()
            for i in range(0, c):
                for x in range(0, r):
                    item = QTableWidgetItem(str(i + x))
                    item.setTextAlignment(Qt.AlignLeft | Qt.AlignCenter)
                    item.setBackgroundColor(Qt.red)
                    self.table.setItem(x, i, item)
    
        def liveChange(self):
            if self.child == None:
                self.child = liveDialog(self.callback, self)  # self表示属于父类,LiveDialog继承父类
            self.child.show()
            self.child.raise_()
            self.child.activateWindow()
    
    
    class liveDialog(QDialog):
        def __init__(self, callback, parent=None):
            super(liveDialog, self).__init__(parent)
            self.callback = callback
            self.c_edit = QLineEdit()
            self.r_edit = QLineEdit()
            layout = QHBoxLayout()
            layout.addWidget(self.c_edit)
            layout.addWidget(self.r_edit)
            self.setLayout(layout)
            self.connect(self.c_edit, SIGNAL("textChanged(QString)"), self.updateUi)
            self.connect(self.r_edit, SIGNAL("textEdited(QString)"), self.updateUi)
    
        def updateUi(self, text):
            c = self.c_edit.text()
            r = self.r_edit.text()
            if c and r:
                self.callback(int(c), int(r))
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        mf = MainForm()
        mf.show()
        app.exec_()

    ++++++++++++++++++++++++++++++++分割线+++++++++++++++++++++++++++++++++++++++

    恶搞弹框

    顾名思义就是父类弹层若干个子窗体,将整个屏幕占满

    clown.ui:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <ui version="4.0">
     3  <class>Dialog</class>
     4  <widget class="QDialog" name="Dialog">
     5   <property name="geometry">
     6    <rect>
     7     <x>0</x>
     8     <y>0</y>
     9     <width>313</width>
    10     <height>163</height>
    11    </rect>
    12   </property>
    13   <property name="windowTitle">
    14    <string>Dialog</string>
    15   </property>
    16   <layout class="QVBoxLayout" name="verticalLayout">
    17    <item>
    18     <layout class="QGridLayout" name="gridLayout">
    19      <item row="0" column="0">
    20       <widget class="QPushButton" name="pushButton">
    21        <property name="text">
    22         <string>选择</string>
    23        </property>
    24       </widget>
    25      </item>
    26      <item row="1" column="0">
    27       <widget class="QPushButton" name="pushButton_2">
    28        <property name="text">
    29         <string>查看</string>
    30        </property>
    31       </widget>
    32      </item>
    33      <item row="2" column="0">
    34       <widget class="QPushButton" name="pushButton_3">
    35        <property name="text">
    36         <string>独立弹出任务栏</string>
    37        </property>
    38       </widget>
    39      </item>
    40     </layout>
    41    </item>
    42   </layout>
    43  </widget>
    44  <resources/>
    45  <connections/>
    46 </ui>

    转换为py

    clown.py:

     1 # -*- coding: utf-8 -*-
     2 
     3 # Form implementation generated from reading ui file 'clown.ui'
     4 #
     5 # Created: Wed Mar 18 15:17:11 2015
     6 #      by: PyQt4 UI code generator 4.10.3
     7 #
     8 # WARNING! All changes made in this file will be lost!
     9 
    10 from PyQt4 import QtCore, QtGui
    11 
    12 try:
    13     _fromUtf8 = QtCore.QString.fromUtf8
    14 except AttributeError:
    15     def _fromUtf8(s):
    16         return s
    17 
    18 try:
    19     _encoding = QtGui.QApplication.UnicodeUTF8
    20     def _translate(context, text, disambig):
    21         return QtGui.QApplication.translate(context, text, disambig, _encoding)
    22 except AttributeError:
    23     def _translate(context, text, disambig):
    24         return QtGui.QApplication.translate(context, text, disambig)
    25 
    26 class Ui_Dialog(object):
    27     def setupUi(self, Dialog):
    28         Dialog.setObjectName(_fromUtf8("Dialog"))
    29         Dialog.resize(313, 163)
    30         self.verticalLayout = QtGui.QVBoxLayout(Dialog)
    31         self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
    32         self.gridLayout = QtGui.QGridLayout()
    33         self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
    34         self.pushButton = QtGui.QPushButton(Dialog)
    35         self.pushButton.setObjectName(_fromUtf8("pushButton"))
    36         self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
    37         self.pushButton_2 = QtGui.QPushButton(Dialog)
    38         self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
    39         self.gridLayout.addWidget(self.pushButton_2, 1, 0, 1, 1)
    40         self.pushButton_3 = QtGui.QPushButton(Dialog)
    41         self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
    42         self.gridLayout.addWidget(self.pushButton_3, 2, 0, 1, 1)
    43         self.verticalLayout.addLayout(self.gridLayout)
    44 
    45         self.retranslateUi(Dialog)
    46         QtCore.QMetaObject.connectSlotsByName(Dialog)
    47 
    48     def retranslateUi(self, Dialog):
    49         Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
    50         self.pushButton.setText(_translate("Dialog", "选择", None))
    51         self.pushButton_2.setText(_translate("Dialog", "查看", None))
    52         self.pushButton_3.setText(_translate("Dialog", "独立弹出任务栏", None))
    53 
    54 
    55 if __name__ == "__main__":
    56     import sys
    57     app = QtGui.QApplication(sys.argv)
    58     Dialog = QtGui.QDialog()
    59     ui = Ui_Dialog()
    60     ui.setupUi(Dialog)
    61     Dialog.show()
    62     sys.exit(app.exec_())

    逻辑页面MainClown.py:

      1 # -*- coding: UTF8 -*-
      2 
      3 from PyQt4 import QtCore, QtGui
      4 from clown import Ui_Dialog
      5 import sys
      6 from PyQt4.QtGui import *
      7 import ClownRcc
      8 import random
      9 
     10 class MainClown(QtGui.QWidget):
     11     def __init__(self, parent=None):
     12         super(MainClown, self).__init__(parent)
     13         self.Ui = Ui_Dialog()
     14         self.Ui.setupUi(self)
     15         self.setWindowIcon(QtGui.QIcon(':safe.ico'))
     16         self.Ui.pushButton.clicked.connect(self.clickDig)
     17         self.Ui.pushButton_2.clicked.connect(self.multDig)
     18         self.Ui.pushButton_3.clicked.connect(self.taskDig)
     19 
     20     # 循环alert   #--- 一个任务栏,一个dialog
     21     def clickDig(self):
     22         self.a=Icon(self)
     23         self.a.setWindowFlags(QtCore.Qt.Window)
     24         dictmsg = {1:u'海阔天空',2:u'心存梦想',3:u'勇往直前'}
     25         for i in range(0, 5):
     26             x = random.randint(100, 600)
     27             y = random.randint(100, 600)
     28             iskey = dictmsg.has_key(i)
     29             if not iskey:
     30                 msg = u'确定要打开吗?'
     31             else:
     32                 msg = dictmsg[i]
     33 
     34             OK = QtGui.QMessageBox.question(self, (u'提示'),(msg),QtGui.QMessageBox.Yes , QtGui.QMessageBox.No)
     35             if OK == QtGui.QMessageBox.No:
     36                 return False
     37             self.a.move(x, y)
     38             self.a.show()     # pos = self.previewWindow.pos()  随机self.previewWindow.move(pos) 到pos上    pos.setX(0)     pos.setY(0)
     39 
     40 
     41 
     42     # 弹出另外一个任务栏   #--- 两个任务栏  关闭父窗体 子窗体不关闭
     43     def taskDig(self):
     44         self.b = Icon()
     45         self.b.move(500, 600)
     46         self.b.show()
     47 
     48         self.d = Icon()
     49         self.d.move(600,700)
     50         self.d.show()
     51 
     52 
     53     # 恶搞   #--- 多个任务栏  关闭父窗体 子窗体关闭  依赖于 closeEvent事件 QtCore.QCoreApplication.quit()
     54     def multDig(self):
     55         screenxy = QtGui.QDesktopWidget().screenGeometry() #计算屏幕分辨率
     56         OK = QtGui.QMessageBox.warning(self, (u'提示'),(u'确定要打开吗?打开会后悔的!'),QtGui.QMessageBox.Yes , QtGui.QMessageBox.No)
     57         if OK == QtGui.QMessageBox.Yes:
     58             rounds = 30
     59             vardict = {}
     60             for ii in range(rounds):
     61                 vardict['a'+str(ii)] = 'a'+str(ii)
     62 
     63             for i in range(rounds):
     64                 self.adf=Icon()
     65                 setattr(self, vardict['a'+str(i)], Icon()) #第一个参数是对象,这里的self其实就是test.第二个参数是变量名,第三个是变量值
     66                 
     67                 x = random.randint(20, screenxy.width())
     68                 y = random.randint(20, screenxy.height())
     69                 exec("self.a"+str(i)+".move("+str(x)+","+str(y)+")")
     70                 exec("self.a"+str(i)+".show()")
     71 
     72 
     73     # 重载关闭按钮   #--- 继承closeEvent ==QtCore.QCoreApplication.quit() 多个任务栏     关闭父窗体  子窗体也关闭
     74     def closeEvent(self, event):
     75         QtCore.QCoreApplication.quit()
     76 
     77 
     78 
     79 
     80 
     81 
     82 
     83 class Icon(QtGui.QDialog):
     84     def __init__(self, parent=None):
     85         QtGui.QWidget.__init__(self, parent)
     86         palette1 = QtGui.QPalette(self)
     87         palette1.setBrush(self.backgroundRole(), QtGui.QBrush(QtGui.QPixmap(':bluesky.jpg')))   # 设置背景图片
     88         self.setPalette(palette1)
     89         self.setGeometry(300, 300, 250, 150)
     90         self.setWindowTitle('Icon')
     91         mylayout = QVBoxLayout()
     92         self.setLayout(mylayout)
     93 
     94 
     95 
     96 
     97 if __name__ == '__main__':
     98     app = QtGui.QApplication(sys.argv)
     99     MainApp = MainClown()
    100     MainApp.show()
    101     sys.exit(app.exec_())

  • 相关阅读:
    关于各种编程语言调用C星寻路插件的例子
    练习作品11:语音识别 准确度70%
    练习作品10:被一个傻叉坑了 要求把串口 封装到DLL中调用;
    Dynamics CRM 构建IN查询
    初识Spark2.0之Spark SQL
    从Dynamics CRM2011到Dynamics CRM2016的升级之路
    Dynamics CRM2011 导入解决方案报根组件插入错误的解决方法
    基于hadoop的BI架构
    Dynamics CRM 不同的站点地图下设置默认不同的仪表板
    Dynamics CRM 打开数据加密报错及修改用户邮件保存报错的解决方法
  • 原文地址:https://www.cnblogs.com/dcb3688/p/4366355.html
Copyright © 2020-2023  润新知