简体   繁体   中英

PyQT4 how to using def from others model

This code works:

import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), self.strona)

    def strona(self):
        self.ui.webView.setUrl(QtCore.QUrl("http://plemiona.pl"))

but this

funkcje.py

from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow

def strona():
        self.ui.webView.setUrl(QtCore.QUrl("http://xxxx.pl"))



import sys, time, funkcje
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), funkcje.strona)

doesn't work...

Traceback (most recent call last):
  File "C:\Python33\liczbapierwsza\TribalWarsBot\funkcje.py", line 5, in przejdz_na_strone_plemion
    QtGui.QWidget.__init__(self, parent)
NameError: global name 'self' is not defined

how to import function from funkcje.py and use in ex run.py

strona needs to have access to the class instance, self. I'm not sure how you would go about passing the self parameter using Qt, but you can always write a wrapper function as part of your class that calls strona and passes the self parameter. Or import types and add types.MethodType(funkcje.strona, self, MyForm) to the class constructor( __init__ ). That adds funkcje.strona to the class. Note that the latter is untested by me.

EDIT: Here is what to do:

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        types.MethodType(strona, self, MyForm) 
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), strona)

Note: This is untested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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