Python GUI QCore.Aplication error - user-interface

I had tried various workarounds about this problem and tried to fix code according to other examples, but ultimately I had failed to make a workable code. While I do have idea of why it fails, I lack skill to create a workaround about this error. Could you please help me with making this code to work?
The problem:
Then I press ''Duomenų apdorojimas'' and proceed to press ''Pavaizduoti signalą'' I get error saying: QCoreApplication::exec: The event loop is already running. I tried various workarounds about this and some legacy code is left inside my functions. I will tidy and optimize my code later, I just need to know how to work properly with GUI in order to avoid this problem. If needed I will send you entire program with txt files, but this part is essential and here problem arises.
import os
import os.path
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from tkinter import *
import tkinter.messagebox
import sys
from functools import partial
import matplotlib.pyplot as p
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 300)
self.setWindowTitle("")
self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
openFile = QtGui.QAction("&Atverkite duomenų failą", self)
openFile.setShortcut("Ctrl+Q")
openFile.setStatusTip('Duomenų failas')
openFile.triggered.connect(self.file_open)
extractAction = QtGui.QAction("&Duomenys iš Arduino", self)
extractAction.setShortcut("Ctrl+W")
extractAction.setStatusTip('Prijunkite iš Arduino ateinančius duomenis')
extractAction.triggered.connect(self.upload_usb)
saveFile = QtGui.QAction("&Įšsaugoti failą", self)
saveFile.setShortcut("Ctrl+E")
saveFile.setStatusTip('Nurodykite failo direktoriją bei pavadinimą')
saveFile.triggered.connect(self.file_save)
quitFile = QtGui.QAction("&Išeiti", self)
quitFile.setShortcut("Ctrl+R")
quitFile.setStatusTip('Programa bus uždaryta')
quitFile.triggered.connect(self.close_application)
openEditor = QtGui.QAction("&Skaitytuvas", self)
openEditor.setShortcut("Ctrl+T")
openEditor.setStatusTip('Skaitytuvas visados įjungtas')
openEditor.triggered.connect(self.editor)
additionalData = QtGui.QAction("&Paciento duomenys", self)
additionalData.setShortcut("Ctrl+A")
additionalData.setStatusTip('Įveskite paciento amžiaus grupę')
additionalData.triggered.connect(self.group)
dataProcessing = QtGui.QAction("&Filtruoti signalą", self)
dataProcessing.setShortcut("Ctrl+S")
dataProcessing.setStatusTip('Bus atliekami signalo apdorojimo procesai')
dataProcessing.triggered.connect(self.editor)
showGraph = QtGui.QAction("&Pavaizduoti signalą", self)
showGraph.setShortcut("Ctrl+D")
showGraph.setStatusTip('Bus atvaizduotas šiuo metu turimas signalas')
showGraph.triggered.connect(self.close_application)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&Progamos funkcijos')
fileMenu.addAction(openFile)
fileMenu.addAction(extractAction)
fileMenu.addAction(saveFile)
fileMenu.addAction(quitFile)
resultsMenu = mainMenu.addMenu("&Duomenų apdorojimas")
resultsMenu.addAction(dataProcessing)
resultsMenu.addAction(showGraph)
editorMenu = mainMenu.addMenu("&Programos nustatymai")
editorMenu.addAction(openEditor)
editorMenu.addAction(additionalData)
self.statusBar()
self.home()
def openFile(self,n):
print(n)
def home(self):
self.show()
def close_application(self):
graphics()
sys.exit()
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()

Well, it turns out that I was trying to open semi-new program in graphics(). I found out how not to create GUI. Thank you for you help, but I have found out solution. For the next time I will post code in onedrive or something in order for people to get whole program with its supporting documents.

Related

Microsoft Azure Speech-to-Text MVC application

I'm working on an application that uses the Microsoft Cognitive services Speech-to-Text API. I'm trying to create a GUI where the transcribed text should show up in a textbox once the start button is pushed and the transcription is stopped once a stop-button is pressed. I'm pretty new to creating GUI's and have been using PyQt5. I have divided the application according to MVC (Model-View-Controller). The code for the GUI is as follows:
import sys
import time
from functools import partial
import azure.cognitiveservices.speech as speechsdk
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class test_view(QMainWindow):
def __init__(self):
super().__init__()
self.generalLayout = QVBoxLayout()
self._centralWidget = QWidget(self)
self.setCentralWidget(self._centralWidget)
self._centralWidget.setLayout(self.generalLayout)
self._createApp()
def _createApp(self):
self.startButton = QPushButton('Start')
self.stopButton = QPushButton('Stop')
buttonLayout = QHBoxLayout()
self.startButton.setFixedWidth(220)
self.stopButton.setFixedWidth(220)
buttonLayout.addWidget(self.startButton)
buttonLayout.addWidget(self.stopButton)
self.text_box = QTextEdit()
self.text_box.setReadOnly(True)
self.text_box.setFixedSize(1500, 400)
layout_text = QHBoxLayout()
layout_text.addWidget(self.text_box)
layout_text.setAlignment(Qt.AlignCenter)
self.generalLayout.addLayout(buttonLayout)
self.generalLayout.addLayout(layout_text)
def appendText(self, text):
self.text_box.append(text)
self.text_box.setFocus()
def clearText(self):
return self.text_box.setText('')
class test_ctrl:
def __init__(self, view):
self._view = view
def main():
application = QApplication(sys.argv)
view = test_view()
view.showMaximized()
test_ctrl(view=view)
sys.exit(application.exec_())
if __name__ == "__main__":
main()
The Speech-to-Text Transcribe code is:
import azure.cognitiveservices.speech as speechsdk
import time
def setupSpeech():
speech_key, service_region = "speech_key", "service_region"
speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)
return speech_recognizer
def main():
speech_recognizer = setupSpeech()
done = False
def stop_cb(evt):
print('CLOSING on {}'.format(evt))
speech_recognizer.stop_continuous_recognition()
nonlocal done
done = True
all_results = []
def handle_final_result(evt):
all_results.append(evt.result.text)
speech_recognizer.recognizing.connect(lambda evt: print(evt))
speech_recognizer.recognized.connect(handle_final_result)
speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)
speech_recognizer.start_continuous_recognition()
while not done:
time.sleep(.5)
print(all_results)
if __name__ == "__main__":
main()
I know for sure that both of the pieces of code work, but I'm not sure how to build the speech-to-text code into the MVC code. I think it should work with a model and it should be connected through the controller to the view. I tried doing this in multiple ways but I just can't figure it out. I also figured I need some kind of threading to keep the code from freezing the GUI. I hope someone can help me with this.
You need to replace this part
print(all_results)
and push all_results asynchronously to ur code for processing the text.
If not, expose a button in the UI to invoke the speech_recognizer.start_continuous_recognition() as a separate function and pick the results to process. This way you can avoid freezing the UI

tkinter GUI freezes while plotting voltages of an Arduino

I am just trying to write a GUI to help me while measuring. For now, I want to be able to plot -Voltages for example- in real-time from my Arduino UNO. Sadly this code just works fine for around 5 seconds, after this the tkinter windows freezes. Amazingly the v and t list works. Would you please give me a hint to fix this problem? I just spend hours.
from pyfirmata import Arduino, util
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
import time
import threading
board=Arduino('COM3')
iterator = util.Iterator(board)
iterator.start()
Tvl = board.get_pin('a:0:i')
class mclass(threading.Thread):
def __init__(self, window):
threading.Thread.__init__(self)
self.window = window
self.box = Entry(window)
self.button = Button (window, text="check", command=self.plot)
self.box.pack ()
self.button.pack()
self.t=[]
self.v=[]
self.fig = Figure(figsize=(6,6))
self.a = self.fig.add_subplot(111)
self.a.invert_yaxis()
self.a.set_title ("Estimation Grid", fontsize=16)
self.a.set_ylabel("Y", fontsize=14)
self.a.set_xlabel("X", fontsize=14)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.window)
self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=False)
def plot (self):
global t,v
clock=time.perf_counter()
while time.perf_counter()-clock<=float(self.box.get()):
self.v.append(Tvl.read())
self.t.append(time.perf_counter()-clock)
if len(self.v)>=25:
del self.v[0]
del self.t[0]
self.a.clear()
self.a.plot(self.t,self.v)
self.canvas.draw()
window= Tk()
t= mclass(window)
t.start()
window.mainloop()
I thank you for your comments. In the end patthoyts hint worked quite well. I would be verry interested why while loops in this case dont work.
Beneath ist the new stable Code with some more Features added.
thanks and greets peterudo
from pyfirmata import Arduino, util
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
import time
import threading
board=Arduino('COM3')
iterator = util.Iterator(board)
iterator.start()
Tvl = board.get_pin('a:0:i')
class mclass(threading.Thread):
def __init__(self, window):
threading.Thread.__init__(self)
self.window = window
self.box = Entry(window)
self.box.pack ()
self.button = Button (window, text="check", command=self.plot)
self.button.pack()
self.button2 = Button(window,text="stop", command=self.start_stop)
self.button2.pack()
self.w=Scale(window, from_=0, to=10000)
self.w.pack()
self.w2=Scale(window, from_=0, to=100000)
self.w2.pack()
self.t=[]
self.v=[]
self.ss=True
self.fig = Figure(figsize=(6,6))
self.a = self.fig.add_subplot(111)
self.a.invert_yaxis()
self.a.set_title ("Estimation Grid", fontsize=16)
self.a.set_ylabel("Y", fontsize=14)
self.a.set_xlabel("X", fontsize=14)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.window)
self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=False)
def plot (self):
window.after(10, self.plot)
if self.ss==True:
self.v.append(Tvl.read())
self.t.append(time.perf_counter())
if self.t[0]<self.t[len(self.t)-1]-0.0001*self.w2.get():
del self.v[0]
del self.t[0]
self.a.clear()
self.a.set_ylim(Tvl.read()-0.0001*self.w.get(),Tvl.read()+0.0001*self.w.get())
self.a.set_xlim(self.t[len(self.t)-1]-0.001*self.w2.get()+1,time.perf_counter())
self.a.plot(self.t,self.v)
self.canvas.draw()
def start_stop(self):
if self.ss==True:
self.ss=False
else:
self.ss=True
window= Tk()
t= mclass(window)
t.start()
window.mainloop()

How to display an icon in the systray reflecting NumLk state

My computer doesn't have any way of letting me know if my NumLk is on or off, so I am trying to add an icon in my systray that will changed depending on the state of my NumLk. This .py will always be running when my computer is on.
So far I was able to mix 3 codes and I am able to display the icon in the systray but it doesn't get updated when the state of NumLk change. Actually if I press NumLk twice, I still get the same icon (the on one) and I get this error:
QCoreApplication::exec: The event loop is already running
File "\systray_icon_NumLk_on_off.py", line 21, in on_key_press
main(on)
File "\systray_icon_NumLk_on_off.py", line 46, in main
sys.exit(app.exec_())
SystemExit: -1
My code may not be the best way to do it, so any alternative is welcome! Here is what I came up so far:
#####get the state of NumLk key
from win32api import GetKeyState
from win32con import VK_NUMLOCK
#how to use: print(GetKeyState(VK_NUMLOCK))
#source: http://stackoverflow.com/questions/21160100/python-3-x-getting-the-state-of-caps-lock-num-lock-scroll-lock-on-windows
#####Detect if NumLk is pressed
import pyglet
from pyglet.window import key
window = pyglet.window.Window()
#source: http://stackoverflow.com/questions/28324372/detecting-a-numlock-capslock-scrlock-keypress-keyup-in-python
on=r'on.png'
off=r'off.png'
#window.event
def on_key_press(symbol, modifiers):
if symbol == key.NUMLOCK:
if GetKeyState(VK_NUMLOCK):
#print(GetKeyState(VK_NUMLOCK))#should be 0 and 1 but
main(on)
else:
main(off)
#window.event
def on_draw():
window.clear()
### display icon in systray
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
#source: http://stackoverflow.com/questions/893984/pyqt-show-menu-in-a-system-tray-application - add answer PyQt5
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
def main(image):
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
pyglet.app.run()
The reason for QCoreApplication::exec: The event loop is already running is actually because you're trying to start app.run() twice. Qt will notice there's already an instance running and throw this exception. When instead, what you want to do is just swap the icon in the already running instance.
Your main problem here is actually the mix of libraries to solve one task if you ask me.
Rather two tasks, but using Qt5 for the graphical part is fine tho.
The way you use Pyglet is wrong from the get go.
Pyglet is intended to be a highly powerful and effective graphics library where you build a graphics engine ontop of it. For instance if you're making a game or a video-player or something.
The way you use win32api is also wrong because you're using it in a graphical window that only checks the value when a key is pressed inside that window.
Now, if you move your win32api code into a Thread (a QtThread to be precise) you can check the state no matter if you pressed your key inside your graphical window or not.
import sys
import win32api
import win32con
from PyQt5 import QtCore, QtGui, QtWidgets
from threading import Thread, enumerate
from time import sleep
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(QtWidgets.qApp.quit)
self.setContextMenu(menu)
class KeyCheck(QtCore.QThread):
def __init__(self, mainWindow):
QtCore.QThread.__init__(self)
self.mainWindow = mainWindow
def run(self):
main = None
for t in enumerate():
if t.name == 'MainThread':
main = t
break
while main and main.isAlive():
x = win32api.GetAsyncKeyState(win32con.VK_NUMLOCK)
## Now, GetAsyncKeyState returns three values,
## 0 == No change since last time
## -3000 / 1 == State changed
##
## Either you use the positive and negative values to figure out which state you're at.
## Or you just swap it, but if you just swap it you need to get the startup-state correct.
if x == 1:
self.mainWindow.swap()
elif x < 0:
self.mainWindow.swap()
sleep(0.25)
class GUI():
def __init__(self):
self.app = QtWidgets.QApplication(sys.argv)
self.state = True
w = QtWidgets.QWidget()
self.modes = {
True : SystemTrayIcon(QtGui.QIcon('on.png'), w),
False : SystemTrayIcon(QtGui.QIcon('off.png'), w)
}
self.refresh()
keyChecker = KeyCheck(self)
keyChecker.start()
sys.exit(self.app.exec_())
def swap(self, state=None):
if state is not None:
self.state = state
else:
if self.state:
self.state = False
else:
self.state = True
self.refresh()
def refresh(self):
for mode in self.modes:
if self.state == mode:
self.modes[mode].show()
else:
self.modes[mode].hide()
GUI()
Note that I don't do Qt programming often (every 4 years or so).
So this code is buggy at it's best. You have to press Ctrl+C + Press "Exit" in your menu for this to stop.
I honestly don't want to put more time and effort in learning how to manage threads in Qt or how to exit the application properly, it's not my area of expertis. But this will give you a crude working example of how you can swap the icon in the lower corner instead of trying to re-instanciate the main() loop that you did.

Unable to implement mpl_connect

I'm working on a GUI that basically hold multiple widgets that each contain a figure as well as a few buttons/whatever. One of the figures is supposed to be interactive, calling a function whenever the user clicks on any part of the plot. Yet I can't get the function to fire using mpl_connect, even after playing with focus and whatnot. I'm somewhat new to PySide/Qt, so I don't exactly understand why my code is behaving like this (I've been searching for days for a solution, but haven't found anything about it).
I used Qt Designer to create the layout for the GUI. I'm using Spyder from Anaconda 2.2.0 (32-bit), Python 2.7, and PySide to develop the GUI. If it's any help, I come from more of a MATLAB background where I developed a full version of the GUI I'm trying to make in Python.
Below is the relevant code (scroll down a bit to see where the problem is):
from PySide import QtCore, QtGui
from PySide.QtCore import *
from PySide.QtGui import *
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
from PySide.QtGui import QPalette, QCursor
import matplotlib.colors as colors
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1316, 765)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(75, 40, 375, 490))
self.widget.setObjectName("widget")
color = self.centralwidget.palette().color(QPalette.Window)
self.leftPlot = MatplotlibWidget(None,'','','',False,color)
self.setupPlot(self.widget,self.leftPlot)
self.leftPlot.figure.tight_layout()
self.leftImage = self.leftPlot.axes.imshow(self.defaultSlide, cmap = mymap)
Snippet of interest:
self.leftPlot.figure.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
self.leftPlot.figure.canvas.setFocus()
cid = self.leftPlot.figure.canvas.mpl_connect('button_release_event', self.getCoordinates) # doesn't get called
plt.show()
def getCoordinates(self, event):
print 'dasdsadadsa'
print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)
The rest:
class MatplotlibWidget(FigureCanvas):
def __init__(self, parent=None,xlabel='x',ylabel='y',title='Title',showTicks=False,color=None):
super(MatplotlibWidget, self).__init__(Figure())
self.setParent(parent)
if color != None:
self.figure = Figure(facecolor=(color.red()/256.0,color.green()/256.0,color.blue()/256.0),frameon=0)
else:
self.figure = Figure(frameon=0)
self.canvas = FigureCanvas(self.figure)
self.axes = self.figure.add_subplot(111)
self.axes.set_xlabel(xlabel)
self.axes.set_ylabel(ylabel)
self.axes.set_title(title)
self.axes.get_xaxis().set_visible(showTicks)
self.axes.get_yaxis().set_visible(showTicks)
class ControlMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ControlMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
plt.show()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
I'm aware the code is messy, but any input is greatly appreciated.
Update (2015-09-04) : I've updated the MWE I provided as part of my original answer to use instead the approach that is suggested in the matplotlib documentation to embed a mpl figure in an application. This approach does not use the pyplot interface (as in my original answer) and use the Object Oriented API of mpl instead. Also, since all the mpl artists (figure, axes, etc.) know each other, there is no need to explicitly create new class variables. This allows a structure of code that is, IMO, easier to read and to maintain.
The problem comes from the fact that you are not connecting correctly your event to self.leftPlot (FigureCanvasQTAgg), but to self.leftPlot.figure.canvas (FigureCanvasQTAgg.figure.FigureCanvasQTAgg) instead. You are creating a canvas within a canvas in the MatplotlibWidget class (which is already a subclass of FigureCanvasQTAgg). You only need to create one mpl canvas, pass a figure to it, and then connect the event to it directly.
I've put together a MWE to demonstrate how this can be done using the Object Oriented API of Matplotlib as suggested in the documentation:
from PySide import QtGui
import numpy as np
import sys
import matplotlib as mpl
mpl.use('Qt4Agg')
mpl.rcParams['backend.qt4']='PySide'
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
class ControlMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ControlMainWindow, self).__init__(parent)
self.setupUi()
def setupUi(self):
figure = mpl.figure.Figure(figsize=(5, 5))
leftPlot = MatplotlibWidget(figure)
self.setCentralWidget(leftPlot)
class MatplotlibWidget(FigureCanvasQTAgg):
def __init__(self, fig):
super(MatplotlibWidget, self).__init__(fig)
#-- set up an axe artist --
ax = fig.add_axes([0.1, 0.1, 0.85, 0.85])
ax.plot(np.arange(15), np.arange(15))
self.draw()
#---- setup event ----
self.mpl_connect('button_press_event', self.onclick)
def onclick(self, event):
x, y = event.x, event.y
print(x, y)
if x != None and y != None:
ax = self.figure.axes[0]
ax.plot(event.xdata, event.ydata, 'ro')
self.draw()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
The code above results in:

Putting stuff in windows

How can I put stuff in the main window? I want to create a line edit in the main window(beneath the menu bar, maybe with some decription laber in front of it). How is this done? I used grid layout and this box layout, nothing works.
(sry for another trivial question, there are only few tutorials on pyside out there, and most of them only cover how to create single windows with buttons ect.)
import sys
from PySide import QtGui, QtCore, QtWebKit
class FirstClass(QtGui.QMainWindow, QtGui.QWidget):
def __init__(self):
super(FirstClass, self).__init__()
self.startingUI()
def startingUI(self):
self.setWindowTitle('Hauptfenster')
self.resize(800, 400)
self.statusBar()
#Menueinstellungen an sich
menue = self.menuBar()
#Actions des Menues:
#datei menue
menuleiste_datei = menue.addMenu('File')
datei_exit = QtGui.QAction('Exit', self)
datei_exit.setStatusTip('Close the programm')
menuleiste_datei.addAction(datei_exit)
datei_exit.triggered.connect(self.close)
#Einstellungen menue
menuleiste_configurations = menue.addMenu('Configurations')
configurations_settings = QtGui.QAction('Settings', self)
configurations_settings.setStatusTip('Configurations(Settings)')
menuleiste_configurations.addAction(configurations_settings)
configurations_settings.triggered.connect(self.newwindow)
self.lineedit = QtGui.QLineEdit()
self.layout = QtGui.QHBoxLayout()
self.layout.addWidget(self.lineedit)
self.setLayout(self.layout)
self.show()
def newwindow(self):
self.wid = QtGui.QWidget()
self.wid.resize(250, 150)
self.setWindowTitle('NewWindow')
self.wid.show()
def main():
app = QtGui.QApplication(sys.argv)
start = FirstClass()
sys.exit(app.exec_())
if __name__== '__main__':
main()
I do not believe creating a class with a multiple inheritance is recommended best practice. If an attribute is not found in FirstClass, then it searches left to right (QtGui.QMainWindow to QtGui.QWidget). From my perspective, this would turn into a nightmare to support and debug. My guess this is why the self.layout is not working properly.
I made separate classes for QtGui.QMainWindow and QtGui.QWidget. FirstWindowClass sets the central widget as FirstWidgetClass. FirstWidgetClass has your QLineEdit and I went ahead and inserted a label. I changed QHBoxLayout to QGridLayout to help you understand how it works.
Some tips from my learning experiences with Python and Pyside these past couple months:
Remember you can always look at PyQt examples and majority will work directly with PySide modules.
I recommend looking over http://srinikom.github.io/pyside-docs/index.html as a lot of the modules have simple examples.
For my personal project, a lot of the solutions to my Qt questions were in C++ so do not be afraid to convert it to python.
import sys
from PySide import QtGui, QtCore, QtWebKit
class FirstWindowClass(QtGui.QMainWindow):
def __init__(self):
super(FirstWindowClass, self).__init__()
self.setWindowTitle('Hauptfenster')
self.resize(800, 400)
self.statusBar()
# Set central widget that expands to fill your window
self.main_widget = FirstWidgetClass(self)
self.setCentralWidget(self.main_widget)
#Menueinstellungen an sich
menue = self.menuBar()
#Actions des Menues:
#datei menue
menuleiste_datei = menue.addMenu('File')
datei_exit = QtGui.QAction('Exit', self)
datei_exit.setStatusTip('Close the programm')
menuleiste_datei.addAction(datei_exit)
datei_exit.triggered.connect(self.close)
#Einstellungen menue
menuleiste_configurations = menue.addMenu('Configurations')
configurations_settings = QtGui.QAction('Settings', self)
configurations_settings.setStatusTip('Configurations(Settings)')
menuleiste_configurations.addAction(configurations_settings)
configurations_settings.triggered.connect(self.newwindow)
# Open the window
self.show()
def newwindow(self):
self.wid = QtGui.QWidget()
self.wid.resize(250, 150)
self.wid.setWindowTitle('NewWindow')
self.wid.show()
class FirstWidgetClass(QtGui.QWidget):
def __init__(self, parent=None):
super(FirstWidgetClass, self).__init__()
self.label_example = QtGui.QLabel('Enter Data:')
self.lineedit = QtGui.QLineEdit()
self.layout = QtGui.QGridLayout()
self.layout.addWidget(self.label_example, 0, 0)
self.layout.addWidget(self.lineedit, 0, 1)
self.setLayout(self.layout)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
start = FirstWindowClass()
sys.exit(app.exec_())
if __name__== '__main__':
main()

Resources