PyQt5 button click not work in imported class - python

In file index.py this line works fine,
but in imported class similar line won't work! I can't understand why.
Then i click pushButton by mice, it not work, no BtnClck1 method is called and no print-SecondWindowPrint.
But if i call PushButton click programmatically, it works fine.
And PushButton works fine if i make connect from index.py
Here is full code on GitHub github.com/m0x3/test1
Here is code:
index.py
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QMainWindow, QApplication
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Set up the MainWindow from Designer.
uic.loadUi("mw.ui", self)
# Connect up the buttons.
self.pushButton.clicked.connect(self.BtnClck)
self.show()
def BtnClck(self):
# Set up the ContentWindow from Designer.
from form1 import form1
form1(self.mn_general)
self.mn_general.pushButton_2.clicked.connect(form1.BtnClck1) #this works fine
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
form1.py
from PyQt5 import uic
class form1:
def __init__(self, obj):
super().__init__()
uic.loadUi("form1.ui", obj)
obj.pushButton.setText('TextChanged on init') #this works fine
obj.pushButton.clicked.connect(self.BtnClck1) #this NOT works
obj.pushButton.click() #this works fine!
def BtnClck1(self):
print('SecondWindowPrint')

MainWindow.mn_general.pushButton_2 calls form1.BtnClck1 as a static function. it's not clear but it works.
If it is good for you, you can define form1.BtnClck1 as static function:
class form1:
def __init__(self, obj):
...........
#staticmethod
def BtnClck1():
print('SecondWindowPrint')
Another way (better way) is put instance of form1 class in a public variable in MainWindow class. You can change BtnClck function in Index.py like this:
def BtnClck(self):
# Set up the ContentWindow from Designer.
from form1 import form1
self.Form=form1(self.mn_general,5)
self.mn_general.pushButton_2.clicked.connect(form1.BtnClck1) #this works fine

Related

How to Import Pyqt5 Widget In Another File

First File first.py
import pyqt5py
ret=pyqt5py.confirm()
print(ret)
Second File Having PYQT5 name: pyqt5py.py
import sys
from PyQt5 import QtWidgets, uic
class Ui(QtWidgets.QDialog):
def __init__(self,button1='Ok',button2='Cancel',text='Are You Sure?'):
super(Ui, self).__init__() # Call the inherited classes __init__ method
uic.loadUi('dialog.ui', self) # Load the .ui file
# Show the GUI
self.pushButton1.clicked.connect(lambda: self.click(1))
self.pushButton2.clicked.connect(lambda: self.click(2))
self.label.setText(text)
self.pushButton1.setText(button1)
self.pushButton2.setText(button2)
self.show()
def click(self,args):
print(self)
return self.sender().text()
app = QtWidgets.QApplication(sys.argv) # Create an instance of QtWidgets.QApplication
def confirm():
def pressed():
return 'clicked'
window = Ui(button1='Ok',button2='Cancel',text='Are You Sure?') # Create an instance of our class
print(window)
window.pushButton1.clicked.connect(pressed)
app.exec_() # Start the application
but i dont know what changes should i do make my first.py to work,i have correctly made the pyqt5 file but i dont know how to add def to call it for confirm
#######################
I Updated My Second File
As suggested by bfris you should rewrite the last lines of pyqt5py.py as follows:
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui(button1='Ok',button2='Cancel',text='Are You Sure?')
app.exec_()
That way you can run this file directly for debbugging purposes, but also import it elsewhere.
To use your widget in first.py you need to create an instance of it there.
first.py:
from pyqt5py.py import UI
app = QtWidgets.QApplication(sys.argv)
window = Ui(button1='Ok',button2='Cancel',text='Are You Sure?')
app.exec_()
Usually I use a QDialog within a Qt environment where it is opened from a QMainWindow and also returning which button was clicked to the QMainWindow.
However as I understand you would like to run another program and in between open your UI? I am not experienced doing that but it seems to me that its exec method does exactly that though you should read this discussion about a bug related to it.
Alternatively in first.py you connect the pushbutton's clicked signal to a slot, a function there.

PYQT6 and QT designer, after opening second window, buttons wont work

So i am making a GUI to identify seagulls.
I have made some QMainWindow's and would like the user to nagviate through these using buttons.
The first window works fine, and the user gets to the next page.
However, when clicking on buttons on page 2, nothing works, not even printing a simple statement. I am new to this and i am doing something wrong. I tried messing with init but am at a loss.
I am using a function
def openNewPage(self,b):
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
to open a new page by having the buttons clicked on by the user have the name of the next file to be opened.
For example: the button for white head has the text "WhiteHead"
and will the open the file WhiteHead.ui
example:
self.bWhiteHead.clicked.connect(lambda:self.openNewPage(self.bWhiteHead))
Please help me understand why buttons work in one window and not in the next, thank you.
Here is the code:
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
from PyQt6 import uic
import time
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("SeagullPage1.ui",self)
self.setWindowTitle("SEAGULL IDENTIFIER")
self.bBlackHead.clicked.connect(lambda:self.openNewPage(self.bBlackHead))
self.bWhiteHead.clicked.connect(lambda:self.openNewPage(self.bWhiteHead))
def openNewPage(self,b):
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
class WhiteHead(QMainWindow):
def __init__(self):
super().__init__
self.setWindowTitle("SEAGULL IDENTIFIER2")
self.BlackFeetButton.clicked.connect(lambda:self.openNewPage(self.BlackFeetButton))
self.PinkFeetButton.clicked.connect(lambda:self.openNewPage(self.PinkFeetButton))
self.YellowFeetButton.clicked.connect(lambda:self.openNewPage(self.YellowFeetButton))
def openNewPage(self,b):
print("hey")
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
class YellowFeet(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("SEAGULL IDENTIFIER3")
self.RedBeakButton.clicked.connect(lambda:self.openNewPage(self.RedBeakButton))
self.NonReadBeakButton.clicked.connect(lambda:self.openNewPage(self.NonReadBeakButton))
def openNewPage(self,b):
print("hey")
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
if __name__ == "__main__":
app = QApplication(sys.argv)
myApp = MyApp()
myApp.show()
app.exec()
#sys.exit(app.exec_())

Opening another window through pushbutton in GUI in PyQt5

I am new to Python and to PyQt. I have designed GUIs in MATLAB so its been a frustrating new experience. Right now, I have a main window and I want to open another login window on button push. What I have not decided is whether it should return the value of login to the parent window or another window. But either way I need to be able to open the login window through the pushbutton. I have created 2 files declaring the GUI one as a mainwindow and another as Dialog (does not seem like it is inheriting from QDialog though). The other 2 py files are classed calling the UIs separately and work fine. Each have their functions. I am pasting the main.py (mainwindow init and onOpen function code) along with logindialog.py init function code. Kindly help or else I will have to go back to Matlab where I can do this quite easily.`
import sys
from PyQt5 import QtWidgets, QtGui
from LoginDialog import LoginDialog
import UI_MSLDB_Main
from UI_LoginDialog import Ui_LoginDialog
#import Helper
#import Auth
#import TestFeature01
class Main(QtWidgets.QMainWindow, UI_MSLDB_Main.Ui_MSLDatabase):
def _init_(self, parent = None):
QtWidgets.QMainWindow._init_(self)
self.setupUi(self)
self.child = LoginDialog(self)
self.child.setupUi(QtWidgets.QDialog())
# self.createConnections()
self.pushButton_OpenPrimarylist.clicked.connect(self.onOpen)
def onOpen(self):
# window = QtWidgets.QDialog
# self.child = LoginDialog(window, Ui_LoginDialog)
# self.child.show()
# exec('LoginDialog.py')
self.child.show
# self.actionStudy.triggered.connect()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
# LoginDialog(QDialog, Ui_LoginDialog)
# loginDialog = LoginDialog(QDialog, UI_LoginDialog)
# username = loginDialog.username
# password =loginDialog.password
# Helper.dbConnect(username,password)
# isAuth = False
# result = -1
# while not isAuth:
# result = loginDialog.exec()
# if result == LoginDialog.Success or result == LoginDialog.Rejected:
# isAuth = True
# else:
# isAuth = False
result = 1
if result == 1:#LoginDialog.Success:
MSLDatabase = QtWidgets.QMainWindow()
ui = UI_MSLDB_Main.Ui_MSLDatabase()
ui.setupUi(MSLDatabase)
MSLDatabase.show()
# w.show()
app.exec_()
sys.exit(app.exec_())
There were multiple things I tried not knowing which would work. The commented codes are the ones I have tried and failed. LoginDialog class is below.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QMessageBox
import Auth
import Helper
from UI_LoginDialog import Ui_LoginDialog
class LoginDialog(QDialog, Ui_LoginDialog):
Success, Failed, Rejected, username, password = range(0,5)
def _init_(self):
QDialog._init_(self)
self.setupUi(self)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL
(_fromUtf8("accepted()")),self.onAccept)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(_fromUtf8("rejected()")),
self.onReject)

Running python files

I am working on pyqt4 and python26 application.I created forms using qt designer (.ui files).
I converted them to .py and .pyc files.But when i try to run .py file ,python command line comes and goes within a second,the form (corresponding .ui file) cannot be seen...what can be the problem??
this is my code:(.py file)
from DlgAbout_ui import Ui_DlgAbout
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import resources
class DlgAbout(QDialog, Ui_DlgAbout):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setupUi(self)
self.logo.setPixmap( QPixmap( ":/icons/faunalia_logo.png" ) )
text = self.txt.toHtml()
text = text.replace( "$PLUGIN_NAME$", "RT Sql Layer" )
self.txt.setHtml(text)
First, don't use:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
Instead:
from PyQt4 import QtCore, QtGui
And reference the modules explicitly.
class DlgAbout(QtGui.QDialog, Ui_DlgAbout):
etc.
In your code, all you've done is defined a dialog box. You haven't defined any main application to run, or any way to show the dialog box.
For an example, here's a basic main application to run:
from PyQt4 import QtGui
import sys
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.form_widget = FormWidget(self)
self.setCentralWidget(self.form_widget)
class FormWidget(QtGui.QWidget):
def __init__(self, parent):
super(FormWidget, self).__init__(parent)
self.layout = QtGui.QVBoxLayout(self)
self.button = QtGui.QPushButton("Button!")
self.layout.addWidget(self.button)
if __name__ == "__main__":
app = QtGui.QApplication([])
foo = MyMainWindow()
foo.show()
sys.exit(app.exec_())
This defines a main window, and a form (Which MyMainWindow sets up, as you can see).
I then check if this is the main file being run (if __name__ == "__main__":), and I start the application (The app = QtGui.QApplication([]), create the main window, and show the main window.
In your case, you could define a main application like I did, and make it alert your QDialog.
Your python code just imports some modules and then defines a new class. It doesn't do anything with the class it has defined, though. In other words, once Python is done creating the new class, it is finished, and it exits.
I don't know PyQT at all, but most likely you need to start the GUI's main loop, and also instantiate an instance of your new class and pass it to PyQT.

Subclassed QWebView doesn't react to Hyperlink Clicks

This is in Python/PySide.
I am trying to create my own Parental WebBrowser by overloading the PySide.QtWebKit.QWebView widget. Then whenever someone clicks a link on the widget I check to see if we are going to an invalid website, if not we proceed, if yes then I redirect to a generic page.
So I have subclassed the PySide.QtWebKit.QWebView, but I am not receiving notification of when a link is clicked. I have overridden the linkClicked function but the function never runs when a link is clicked?
What am I doing wrong? Why cant my function run/react to the hyperlink click "event"? Do I need to override the webpage object & not this class to react to link clicks?
import PySide.QtWebKit
import sys
from PyQt4 import QtGui
class BrowserWindow( PySide.QtWebKit.QWebView ):
# Class Variables:
def __init__( self, _parent ):
""" Constructor: """
super(BrowserWindow, self).__init__()
PySide.QtWebKit.QWebView(None)
def linkClicked(self, arg__1):
""" Post: """
#print("LINK CLICKED")
#text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
# 'Enter your name:')
self.load("http://yahoo.com")
def main():
app = QtGui.QApplication(sys.argv)
view = BrowserWindow(None) #PySide.QtWebKit.QWebView(None)
view.load("http://google.com")
view.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
There are several problems with the code you posted. Firstly, you are importing both PySide and PyQt4, which is not a good idea. Secondly, QWebView.linkClicked is a signal, not a protected method, so you can't override it. Thirdly, you are passing a string to QWebView.load, when you should be passing a QtCore.QUrl.
However, aside from those problems, you also need to set the linkDelegationPolicy on the web page in order to override its link handling.
Here's an edited version of your code which should fix all the problems:
from PySide import QtCore, QtGui, QtWebKit
class BrowserWindow(QtWebKit.QWebView):
def __init__(self, parent=None):
super(BrowserWindow, self).__init__()
self.linkClicked.connect(self.handleLinkClicked)
def handleLinkClicked(self, url):
print(url.toString())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
view = BrowserWindow()
view.load(QtCore.QUrl("http://google.com"))
view.page().setLinkDelegationPolicy(
QtWebKit.QWebPage.DelegateAllLinks)
view.show()
sys.exit(app.exec_())

Categories