PyQt5 program runs but does not display anything - widgets does not show [duplicate] - python-3.x

First of all, similar questions have been answered before, yet I need some help with this one.
I have a window which contains one button (Class First) and I want on pressed, a second blank window to be appeared (Class Second).
I fiddled with the code copied from this question: PyQT on click open new window, and I wrote this code:
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
import design1, design2
class Second(QtGui.QMainWindow, design2.Ui_MainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setupUi(self)
class First(QtGui.QMainWindow, design1.Ui_MainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.dialog = Second(self)
def on_pushButton_clicked(self):
self.dialog.exec_()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
but on_pressed, this error message appears:
AttributeError: 'Second' object has no attribute 'exec_'
(design1 and design2 have been derived from the Qt designer.)
Any thought would be appreciated.

Here I'm using the show method.
Here is a working example (derived from yours):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
class Second(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
class First(QtGui.QMainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.pushButton = QtGui.QPushButton("click me")
self.setCentralWidget(self.pushButton)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.dialog = Second(self)
def on_pushButton_clicked(self):
self.dialog.show()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you need a new window every time you click the button, you can change the code that the dialog is created inside the on_pushButton_clicked method, like so:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
class Second(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
class First(QtGui.QMainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.pushButton = QtGui.QPushButton("click me")
self.setCentralWidget(self.pushButton)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.dialogs = list()
def on_pushButton_clicked(self):
dialog = Second(self)
self.dialogs.append(dialog)
dialog.show()
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Related

pyqt keypress event in lineedit

i have created a untitled ui where exists one lineedit.
now i want to get the value of whatever i type in lineedit immediately
i figured out it could be done using keypressevent but i exactly didn't understand how to use it in lineedit now
from untitled import *
from PyQt4 import QtGui # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QMainWindow, Ui_Dialog):
def event(self, event):
if type(event) == QtGui.QKeyEvent:
print (event.key())
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
#here i want to get what is keypressed in my lineEdit
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
this is my untitled.py code that i have imported
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(662, 207)
self.lineEdit = QtGui.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(50, 30, 113, 27))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
If you want to get the whole text in the line-edit as it is entered, you can use the textEdited signal. However, if you just want to get the current key that was pressed, you can use an event-filter.
Here is how to use both of these approaches:
class MainWindow(QMainWindow, Ui_Dialog):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.lineEdit.installEventFilter(self)
self.lineEdit.textEdited.connect(self.showCurrentText)
def eventFilter(self, source, event):
if (event.type() == QEvent.KeyPress and
source is self.lineEdit):
print('key press:', (event.key(), event.text()))
return super(MainWindow, self).eventFilter(source, event)
def showCurrentText(self, text):
print('current-text:', text)

Screen functions in PYQT

import sys
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time
import datetime
import re
import random
import csv
from CropClass import *
from Wheat_class import *
from Potato_class import *
win1 = uic.loadUiType("MenuScreen.ui")[0]
win2 = uic.loadUiType("WheatScreen.ui")[0]
win3 = uic.loadUiType("PotatoScreen.ui") [0]
class MenuScreen(QtGui.QMainWindow, win1):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.BtnCreateSimulation.clicked.connect(self.changeSimulation)
def changeSimulation(self):
if self.RdoWheat.isChecked() ==True:
print("Wheat is picked")
new_crop=Wheat()
self.wheatSimulation()
elif self.RdoPotato.isChecked() == True:
print("Potato is picked")
new_crop = Potato()
self.PotatoSimulation()
def wheatSimulation(self):
print("Hello")
self.hide()
WheatWindow.show()
def PotatoSimulation(self):
self.hide()
PotatoWindow.show()
class PotatoScreen(QtGui.QMainWindow, win3):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.BtnBacktoMenu.clicked.connect(self.BackToMain)
def BackToMain(self):
self.hide()
MenuWindow.show()
class WheatScreen(QtGui.QMainWindow, win2):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
new_crop = Wheat()
self.BtnBacktoMenu.clicked.connect(self.BackToMain)
self.BtnManual.clicked.connect(self.ManualCalculate)
def BackToMain(self):
self.hide()
MenuWindow.show()
def ManualCalculate(self):
water = self.spBoxWater.value()
light= self.spBoxLight.value()
print("water", water, "light", light)
def main():
app = QtGui.QApplication(sys.argv)
WheatWindow = WheatScreen(None)
PotatoWindow = PotatoScreen(None)
MenuWindow = MenuScreen(None)
MenuWindow.show()
app.exec_()
if __name__ == "__main__":
main()
I have created a program in Python which simulates the growth rates of crops. The user is able to chose between the crop is wheat or potatoes I am trying to create a GUI using PYQT. The problem I am having is that when I try and load the program the program is not recognizing the other screen layouts. The main function should be setting up the screen layouts

Show sub window in main window

Can't work out how to embed a window in a main window using classes:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Qt4 tutorial using classes
This example will be built
on over time.
"""
import sys
from PyQt4 import QtGui, QtCore
class Form(QtGui.QWidget):
def __init__(self, MainWindow):
super(Form, self).__init__()
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.setGeometry(50, 50, 1600, 900)
new_window = Form(self)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
This is supposed to be the single most basic bit of code using classes. How do I get the second window to show please.
As ekhumoro already pointed out, your widget needs to be a child of your mainWindow. However, I do not think that you need to call show for the widget, since it anyways gets called as soon as its parent (MainWindow) calls show. As mata pointed out correctly, the proper way to add a Widget to a MainWindow instance is to use setCentralWidget. Here is a working example for clarification:
import sys
from PyQt4 import QtGui, QtCore
class Form(QtGui.QWidget):
def __init__(self, parent):
super(Form, self).__init__(parent)
self.lbl = QtGui.QLabel("Test", self)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.setGeometry(50, 50, 1600, 900)
new_window = Form(self)
self.setCentralWidget(new_window)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

Why there is a pythonw window generated when mine QProgressDialog window was auto closed?

I am new to both pyqt and python so I'm sure that my question would seem stupid, so thank you for reading and answer it. It is really helpful.
Here is my source code
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))
class Prog(QDialog):
def __init__(self,parent=None):
super(Prog,self).__init__(parent)
self.start_P()
def start_P(self):
progressDialog=QProgressDialog(self)
progressDialog.setWindowModality(Qt.WindowModal)
progressDialog.setMinimumDuration(5)
progressDialog.setWindowTitle(self.tr("请等待"))
progressDialog.setLabelText(self.tr("拷贝..."))
progressDialog.setCancelButtonText(self.tr("取消"))
progressDialog.setRange(0,100)
progressDialog.setAutoClose(True)
for i in range(101):
progressDialog.setValue(i)
QThread.msleep(10)
if progressDialog.wasCanceled():
return
self.connect(progressDialog,SIGNAL("closed()"))
def main():
app = QApplication(sys.argv)
pp = Prog()
pp.show()
app.exec_()
if __name__ == '__main__':
main()
There are some Chinese characters, but it's irrelevant. The strange part is when I execute this program I would get a window of progress dialog, that is what I want. But when it is auto closed a pythonw window generated automatically.
I was curious about why this pythonw window was generated and want to know how to avoid it.
That's because you are creating your QProgressDialog as child of a QDialog, checkout the line that says progressDialog=QProgressDialog(self). Checkout how this example works:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#---------
# IMPORT
#---------
from PyQt4 import QtGui, QtCore
#---------
# MAIN
#---------
class MyThread(QtCore.QThread):
progress = QtCore.pyqtSignal(int)
_stopped = False
def __init__(self, parent=None):
super(MyThread, self).__init__(parent)
def stop(self):
self._stopped = True
def start(self):
self._stopped = False
super(MyThread, self).start()
def run(self):
for progressNumber in range(101):
self.progress.emit(progressNumber)
self.msleep(22)
if self._stopped:
return
class MyWindow(QtGui.QProgressDialog):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.threadProgress = MyThread(self)
self.threadProgress.progress.connect(self.setValue)
def stop(self):
self.threadProgress.stop()
def start(self):
self.threadProgress.start()
def hideEvent(self, event):
self.close()
if __name__ == "__main__":
import sys
codec = QtCore.QTextCodec.codecForName("utf8")
QtCore.QTextCodec.setCodecForTr(codec)
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.setWindowTitle(main.tr("请等待"))
main.setLabelText(main.tr("拷贝..."))
main.setCancelButtonText(main.tr("取消"))
main.setRange(0,100)
main.canceled.connect(main.stop)
main.show()
main.start()
sys.exit(app.exec_())

How can I by default have all text selected in my lineEdit?

I'd like to be able to have all text highlighted in my lineEdit. However, the default selectAll() doesn't seem to do so.
import sys
from PyQt4 import QtCore, QtGui
from gui import Ui_Form
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.lineEdit.setText("Type something here!")
self.ui.lineEdit.selectAll()
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.ui.textEdit.clear)
QtCore.QObject.connect(self.ui.lineEdit, QtCore.SIGNAL("returnPressed()"), self.add_entry)
def add_entry(self):
self.ui.lineEdit.selectAll()
self.ui.lineEdit.cut()
self.ui.textEdit.append("")
self.ui.textEdit.paste()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
I want to select the text on the lineEdit in the default constructor; however, it doesn't. Any reason for this? What should I be doing instead to accomplish this?

Resources