To solve the closed question, I post full code here.
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
form_class = uic.loadUiType(BASE_DIR "./test.ui")[0]
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
self.button.clicked.connect(self.func)
def func(self, a):
global b
b = a
if __name__ == "__main__" :
app = QApplication(sys.argv)
myWindow = WindowClass()
myWindow.show()
app.exec_()
and also it needs ui file in same directory,
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>298</width>
<height>197</height>
</rect>
</property>
<property name="maximumSize">
<size>
<width>298</width>
<height>197</height>
</size>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget name="centralwidget">
<widget name="button">
<property name="geometry">
<rect>
<x>100</x>
<y>80</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
</widget>
</widget>
<widget name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
In this code,
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
self.button.clicked.connect(self.func(1))
def func(self, a):
global b
b = a
This results in an argument error(TypeError: argument 1 has unexpected type 'NoneType'). Is there any way to use the function func
?
I tried wc = WindowClass()
and changed code into:
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
wc = WindowClass()
self.button.clicked.connect(wc.func(1))
def func(self, a):
global b
b = a
This results in a fatal initializing error(Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow. Python runtime state: initialized Current thread 0x000097e8 (most recent call first):).
The code works perfect when it is:
class WindowClass(QMainWindow, form_class):
def __init__(self) :
super().__init__()
self.setupUi(self)
self.button.clicked.connect(self.func)
def func(self):
global b
b = 1
However, I have to use func
as 2 arguments. How can I do this?
CodePudding user response:
Try using partial:
from functools import partial
self.button.clicked.connect(partial(self.func, 1))
My guess is that connect expects a 0 argument function. Partial fixates the argument and creates a 0 argument function.