I created a button in the QT6 creator and named it scanButton. The button shows up when I run the code. However, I'm running into an issue once I want to bind it to a function. I finally got a result but it shows a new button in the top left and it runs self.close, which is not supposed to be the case.
.ui code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<widget class="QPushButton" name="scanButton">
<property name="geometry">
<rect>
<x>280</x>
<y>210</y>
<width>181</width>
<height>141</height>
</rect>
</property>
<property name="text">
<string>Scan</string>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
.py code:
import os
from pathlib import Path
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
class Widget(QWidget):
def __init__(self):
super(Widget, self).__init__()
self.load_ui()
def load_ui(self):
loader = QUiLoader()
path = os.fspath(Path(__file__).resolve().parent / "form.ui")
ui_file = QFile(path)
ui_file.open(QFile.ReadOnly)
loader.load(ui_file, self)
ui_file.close()
scanButton = QPushButton(self)
scanButton.clicked.connect(self.close)
if __name__ == "__main__":
app = QApplication([])
widget = Widget()
widget.show()
sys.exit(app.exec_())
First of all you need to load your ui file as you did:
self.ui = loader.load('form.ui', None)
self.ui.show()
Then you can call your button with the name like this:
self.ui.scanButton.clicked.connect(self.check)
Note that when you press the button it will go to check
function.
Full code:
class main(QWindow):
def __init__(self):
super().__init__()
loader = QUiLoader()
self.ui = loader.load('form.ui', None)
self.ui.show()
self.ui.scanButton.clicked.connect(self.check)
def check(self):
print('You pressed the button!')