How to input in console while running Qt Application in python? - python

I can't input anything from the user in the terminal while running a PyQt Application.
Actually i am creating something but i can't show the whole code here so there is the main of the code, and believe that i need the fix of it only:
from PyQt4.QtGui import *
import sys
def window():
app = QApplication(sys.argv)
window = QWidget()
btn = QPushButton()
btn.setText("Input In Console")
box = QFormLayout()
box.addRow(btn)
btn.clicked.connect(input_txt)
window.setLayout(box)
window.show()
sys.exit(app.exec_())
def input_txt():
input("Enter you Name ")
if __name__ == "__main__":
window()
And while running as i press the button a disaster of loop starts:
I really tried a lot configuring the solution of this problem but all failed. Hope these information helped, if any question regarding the post then please say in comment.

I don't need this anymore but still i am posting answer for if someone else having problem with the same.
Solution : Use Threads
from PyQt4.QtGui import *
import sys,threading
def window():
app = QApplication(sys.argv)
window = QWidget()
btn = QPushButton()
btn.setText("Input In Console")
box = QFormLayout()
box.addRow(btn)
btn.clicked.connect(input_txt)
window.setLayout(box)
window.show()
sys.exit(app.exec_())
def input_txt():
thread = threading.Thread(target=input)
thread.start()
if __name__ == "__main__":
window()

Related

Auto add dashes to Line Edit PyQt5

Is it possible to auto add dashes to PyQt5 Line Edit while the user enters the data, for example if the user wants to enter 123456789012345, while the user enters it should be entered like 12345-67890-12345. Also if the user enters - at the right position it should be accepted in. This was fairly achievable in tkinter, using re(question here), but I think it might be able to do the same with Qt too.
if __name__ == '__main__':
app = QApplication(sys.argv)
le = QLineEdit()
le.show()
sys.exit(app.exec_())
Ps: I have designed the GUI inside of Qt Designer.
inputMask : QString
This property holds the validation input mask.
More https://doc.qt.io/qt-5/qlineedit.html#inputMask-prop
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
centralWidget = QtWidgets.QWidget()
self.setCentralWidget(centralWidget)
self.lineEdit = QtWidgets.QLineEdit()
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.editingFinished.connect(self.editingFinished)
self.lineEdit.setInputMask("999-9999999;.") # +++
grid = QtWidgets.QGridLayout(centralWidget)
grid.addWidget(self.lineEdit)
def editingFinished(self):
print(f"{self.lineEdit.text()} -> {self.lineEdit.text().replace('-', '')}")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setFont(QtGui.QFont("Times", 22, QtGui.QFont.Bold))
w = MainWindow()
w.show()
sys.exit(app.exec_())

pyqt5 problem :The new window closes immediately [duplicate]

I am getting an issue when trying to open a PyQt window.
The code below is an example of my original code. When I imported the module in import Test and ran test.Start(), I got the following error:
QCoreApplication::exec: The event loop is already running
After some research, I found out it was because I had already already made a QApplication.
test.py....
import sys
def Start():
app = QApplication(sys.argv)
m = myWindow()
m.show()
app.exec_()
class myWindow():....
if __name__ == "__main__":
Start()
So then I read that I could rewrite my code like this and it would fix the error:
test.py....
def Start():
m = myWindow()
m.show()
class myWindow():....
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
Start()
app.exec_()
Now I no longer get the QCoreApplication::exec: The event loop is already running error, but my window closes almost immediately after opening.
You need to keep a reference to the opened window, otherwise it goes out of scope and is garbage collected, which will destroy the underlying C++ object also. Try:
def Start():
m = myWindow()
m.show()
return m
class myWindow():....
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = Start()
app.exec_()
You can also do:
def Start():
global m
m = myWindow()
m.show()
class myWindow():....
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = Start()
app.exec_()
Use the following code. Your problem is in your imports and using "show" as a name for function as far as I assume. You haven't provided what you have written in your class, so it's difficult to guess. But following code works like a charm. ;-)
Best wishes, good luck!
import sys
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
def Start():
m = myWindow()
m.showWid()
sys.exit(app.exec())
class myWindow:
def __init__(self):
self.window = QWidget()
self.window.setWindowTitle("Program Title")
self.window.setFixedWidth(600)
self.window.setStyleSheet("background: #18BEBE;")
def showWid(self):
self.window.show()
if __name__ == "__main__":
Start()

How to run two GUIs in Python in parallel?

We are talking about python 2.7 and PyQt4.
I'm working with an open-source program for the eeg analysis called PyCorder, that received data from a system electrodes-amplifier and plot them in a GUI; we can consider it as a black box for the purposes of this question. I implemented a simple interface with Qt designer. My aim is to run both the PyCorder and my interface at the same time in a way that they can exchange data between them.
Here the lines of the code where my interface is launched:
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I guess it's common to any interface done with Qt designer;
Following, the PyCorder launching part:
def main(args):
print "Starting PyCorder, please wait ...\n"
setpriority(priority=4)
app = Qt.QApplication(args)
try:
win = None
win = MainWindow()
win.showMaximized()
if ShowConfirmationDialog:
accept = Qt.QMessageBox.warning(None, "PyCorder Disclaimer", ConfirmationText,
"Accept", "Cancel", "", 1)
if accept == 0:
win.usageConfirmed = True
app.exec_()
else:
win.close()
else:
win.usageConfirmed = True
app.exec_()
except Exception as e:
tb = GetExceptionTraceBack()[0]
Qt.QMessageBox.critical(None, "PyCorder", tb + " -> " + str(e))
if win != None:
win.close()
# show the battery disconnection reminder
if ShowBatteryReminder and win and win.usageConfirmed:
DlgBatteryInfo().exec_()
print "PyCorder terminated\n"
if __name__ == '__main__':
main(sys.argv)
Is it sufficient to know just these two parts of the respective codes to answer my question? Is there any toolbox that can be useful to reach my goal?
The best idea comes to my mind is to use multi processing libraries in order to run QT several times. multiprocessing is one of the libraries you can use.
There are a number of ways to do this, but I prefer to use a central "window manager" to acts as the owner and inter-communication hub of the two windows. Below is a sample of that technique that will need to be adapted to your needs. Note that I use Qt5. I tested on Qt5, and then attempted to translate to Qt4 without testing. It should be right, but might need a little tweeking.
from PyQt4 import QtCore, QtGui
class WindowManager(QtCore.QObject):
"""
Inheriting from QObject has benefits.
For instance, the WindowManager can not have pyQtSignal members, if needed
"""
def __init__(self):
super(WindowManager, self).__init__()
self.firstWindow = FirstWindow(self)
self.secondWindow = SecondWindow(self)
self.firstWindow.show()
self.secondWindow.show()
class FirstWindow(QtGui.QMainWindow):
def __init__(self, manager):
super(FirstWindow, self).__init__()
self.manager = manager
self.mainWidget = QtGui.QWidget()
self.setCentralWidget(self.mainWidget)
self.mainLayout = QtGui.QVBoxLayout(self.mainWidget)
self.clickyButton = QtGui.QPushButton("Click me")
self.mainLayout.addWidget(self.clickyButton)
self.clickyButton.clicked.connect(self.clickyButtonClicked)
def clickyButtonClicked(self, checked=None):
self.manager.secondWindow.setMessage("Clicky button clicked")
class SecondWindow(QtGui.QMainWindow):
def __init__(self, manager):
super(SecondWindow, self).__init__()
self.manager = manager
self.mainWidget = QtGui.QWidget()
self.setCentralWidget(self.mainWidget)
self.mainLayout = QtGui.QVBoxLayout(self.mainWidget)
self.messageBox = QtGui.QLabel()
self.mainLayout.addWidget(self.messageBox)
def setMessage(self, message):
self.messageBox.setText(message)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
manager = WindowManager()
sys.exit(app.exec_())

PyQT exit error in SPYDER

This is PyQT code that I have to be executed in Spyder. The first time, I executed it, it works well. On the second time, it says:
QWidget: Must construct a QApplication before a QPaintDevice "
I searched for solution but nothing worked for me.
from PyQt4 import QtGui, QtCore
import sys
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
def handleButton(self):
print ('Hello World')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
#sys.exit(app.exec_())
I even commented sys.exit() which some people proposed. Could someone help me to get rid of this error as I am restarting the kernel every other time to execute.
First, your example is not really minimal. You'll observe, that
from PyQt4 import QtGui
if __name__ == '__main__':
app = QtGui.QApplication([])
w = QtGui.QWidget()
w.show()
app.exec_()
already does the trick.
My guess is that the console in which you let this script run twice is not deleting the QApplication (type app in the console you see the variable is still there).
In the second run, the newly created QApplication interferes with the still existing from the old run. They all run within the same console and it depends a bit on what spyder does when running a file.
To circumvent this delete the app before another run:
del app

PyQt dialog closes entire app on exit

I have a PyQt wizard that includes a dialog box that asks the user a question. This dialog box is optional and only for use if the user wants it. A button sends a signal that the app receives and opens the window. The problem I have is that when the dialog is closed, it closes the whole app with it. How do I make sure that when the dialog is closed, the main app stays open and running? Here the code that handles the dialog box:
def new_item(self):
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.exec_()
I tried adding a 'Cancel' button to close it manually but the result was the same, the whole app closed.
QtCore.QObject.connect(self.cancel, QtCore.SIGNAL(_fromUtf8("clicked()")), Dialog.close)
You shouldn't create new QApplication objects in your code, and I am not surprised that destroying that object closes the application.
Your code should look something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.dialog = QtGui.QMessageBox(self)
self.dialog.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
self.dialog.setIcon(QtGui.QMessageBox.Question)
self.dialog.setText("Click on a button to continue.")
self.pushButtonQuestion = QtGui.QPushButton(self)
self.pushButtonQuestion.setText("Open a Dialog!")
self.pushButtonQuestion.clicked.connect(self.on_pushButtonQuestion_clicked)
self.layoutHorizontal = QtGui.QHBoxLayout(self)
self.layoutHorizontal.addWidget(self.pushButtonQuestion)
#QtCore.pyqtSlot()
def on_pushButtonQuestion_clicked(self):
result = self.dialog.exec_()
if result == QtGui.QMessageBox.Ok:
print "Dialog was accepted."
elif result == QtGui.QMessageBox.Cancel:
print "Dialog was rejected."
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
Try to use Dialog.reject instead of Dialog.close
.close() method is being used mith QMainWindow Widget, .reject() with QDialog.
In my case, I had QSystemTrayIcon as an "entry point" to my app instead of QMainWindow or QWidget.
Calling .setQuitOnLastWindowClosed(False) on my main QApplication instance helped, thanks to this answer

Categories

Resources