Pyqt open child widget after close parent crashes - python

I am working with code http://pastebin.com/3JZWP14y to fix my errors in code below. I need to know the proper way to launch another widget/dialog for text entry to my list.
Below was my original code.
I have my app that displays a table, the child widget to add a row opens and closes fine but then my parent crashes. Code to parent is below. The child closes with sys.exit(app.exec_()) The child also opens the todo.p file but closes all pointers to file.
from PyQt4.QtGui import (QMainWindow, QApplication)
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import pickle as p
import sys
import addit
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_MainWindow(object):
def __init__(self):
#app = QApplication(sys.argv)
self.window = QMainWindow()
self.setupUi(self.window)
self.window.show()
#self.d=self.getdata()
self.d={"12345678":["do some stuff here that needs to be in a large cell to wrap text","1",1],"12343378":["do stuff","1",1]}
self.setmydata(self.d)
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(296, 478)
MainWindow.setIconSize(QtCore.QSize(0, 0))
MainWindow.setAnimated(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.tableView = QtGui.QTableWidget(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(20, 50, 261, 391))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableView.sizePolicy().hasHeightForWidth())
self.tableView.setSizePolicy(sizePolicy)
self.tableView.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers)
self.tableView.setDragEnabled(True)
self.tableView.setAlternatingRowColors(True)
self.tableView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
self.tableView.setSortingEnabled(False)
self.tableView.setObjectName(_fromUtf8("tableView"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(20, 10, 121, 31))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(160, 10, 121, 31))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 296, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton.clicked.connect(lambda: self.openaddit())
def openaddit(self):
x=addit.openwindow()
print "clean"
#reload?
def createfile(self,d):
f=open('todo.d',"w")
p.dump(d,f)
f.close
def getdata(self):
if os.path.isfile('todo.p'):
print "here"
d= p.load(open('todo.p', 'r'))
else:
print "here2"
d={}
self.createfile(d)
print d,"hereeeee"
return d
def setmydata(self,d):
self.data = {}
keys=d.keys()
self.data['col1']=keys
self.data['col2']=[]
self.tableView.setRowCount(len(keys))
self.tableView.setColumnCount(2)
self.tableView.setHorizontalHeaderLabels(['SR', 'Notes'])
for i in range(0,len(keys)):
if d[keys[i]][2]==0:
continue
self.tableView.setItem(i, 0, QtGui.QTableWidgetItem(keys[i]))
self.tableView.setItem(i, 1, QtGui.QTableWidgetItem(d[keys[i]][0]))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.tableView.setRowHeight(i,100)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Add New", None))
self.pushButton_2.setText(_translate("MainWindow", "Save", None))
app = QApplication(sys.argv)
frame = Ui_MainWindow()
#frame.show()
app.exec_()
addit.openwindow() calls the below program.
import sys
from PyQt4 import QtCore, QtGui
#import numpy as np
import pickle as p
class MyQDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(MyQDialog, self).__init__(parent)
## Default values
self.d={}
## Create labels and buttons
#self.setObjectName(("Dialog"))
self.resize(400, 279)
self.d ={}
self.buttonBox = QtGui.QDialogButtonBox(self)
self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(("buttonBox"))
self.lineEdit = QtGui.QLineEdit(self)
self.lineEdit.setGeometry(QtCore.QRect(40, 20, 141, 31))
self.lineEdit.setObjectName(("lineEdit"))
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.setGeometry(QtCore.QRect(20, 60, 361, 161))
self.textEdit.setObjectName(("textEdit"))
self.textEdit.setTabChangesFocus(True)
self.spinBox = QtGui.QSpinBox(self)
self.spinBox.setGeometry(QtCore.QRect(260, 21, 61, 31))
self.spinBox.setMinimum(1)
self.spinBox.setObjectName(("spinBox"))
self.label = QtGui.QLabel(self)
self.label.setGeometry(QtCore.QRect(10, 26, 21, 21))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(("label"))
self.label.setText("SR")
self.label_2 = QtGui.QLabel(self)
self.label_2.setGeometry(QtCore.QRect(190, 25, 61, 21))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(("label_2"))
self.label_2.setText("Priority")
self.setTabOrder(self.lineEdit,self.spinBox)
self.setTabOrder(self.spinBox,self.textEdit)
self.lineEdit.setFocus(True)
self.setWindowTitle("Add To Do SR")
self.show()
## Button functions
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(("accepted()")), self.build)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(("accepted()")), self.close)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(("rejected()")), self.cancel)
def cancel(self):
self.close()
def save(self):
#self.close()
return self.d
def build(self):
#if(len(self.lineEdit.text()!=0)
#print len(self.lineEdit.text())
self.d["SR"]=str(unicode(self.lineEdit.text().toUtf8(), encoding="UTF-8"))
self.d["desc"]=str(unicode(self.textEdit.toPlainText().toUtf8(), encoding="UTF-8"))
self.d["p"]=str(self.spinBox.value())
#print self.d
if self.d["SR"]!='':
#print "saving"
f= open('todo.p', 'r+')
load=p.load(f)
f.close()
#print load
tmp2=[]
tmp2.append(self.d["desc"])
tmp2.append(self.d["p"])
tmp2.append(1)
load[self.d['SR']]=tmp2
#print tmp
#print load
f=open('todo.p','w')
p.dump(load,f)
f.close()
print "closed"
self.save
else:
self.d={}
return False
def openwindow():
app = QtGui.QApplication(sys.argv)
edit_params__QD = MyQDialog()
edit_params__QD.exec_()
edit_params__QD.activateWindow()
if edit_params__QD.result() == 0:
d= edit_params__QD.save()
if len(d)==0:
#print "did not add no SR num"
return False
print "exited out"
#sys.exit(app.exex_())

Related

How to print the changing values of QLCD Widget in PyQt4?

I'm a bit new in PyQt4, I've been working on simple GUI which has an QDial and LCD Widget.I've used SIGNAL and SLOT technique,i.e when the QDial is changed it's value will be shown on the LCD Widget.
Similarly i want to print that LCD value in terminal everytime the QDial is changed.How am i supposed to do that?
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(610, 404)
MainWindow.setStatusTip(_fromUtf8(""))
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.dial_1 = QtGui.QDial(self.centralWidget)
self.dial_1.setGeometry(QtCore.QRect(390, 10, 101, 91))
font = QtGui.QFont()
font.setStrikeOut(False)
self.dial_1.setFont(font)
self.dial_1.setMouseTracking(False)
self.dial_1.setFocusPolicy(QtCore.Qt.ClickFocus)
self.dial_1.setStatusTip(_fromUtf8(""))
self.dial_1.setWhatsThis(_fromUtf8(""))
self.dial_1.setAccessibleDescription(_fromUtf8(""))
self.dial_1.setAutoFillBackground(False)
self.dial_1.setSingleStep(1)
self.dial_1.setPageStep(10)
self.dial_1.setProperty("value", 0)
self.dial_1.setSliderPosition(0)
self.dial_1.setWrapping(False)
self.dial_1.setNotchTarget(3.7)
self.dial_1.setNotchesVisible(True)
self.dial_1.setObjectName(_fromUtf8("dial_1"))
self.lcdNumber_1 = QtGui.QLCDNumber(self.centralWidget)
self.lcdNumber_1.setGeometry(QtCore.QRect(500, 40, 81, 41))
self.lcdNumber_1.setFrameShape(QtGui.QFrame.Panel)
self.lcdNumber_1.setLineWidth(2)
self.lcdNumber_1.setDigitCount(4)
self.lcdNumber_1.setSegmentStyle(QtGui.QLCDNumber.Flat)
self.lcdNumber_1.setObjectName(_fromUtf8("lcdNumber_1"))
self.label_1 = QtGui.QLabel(self.centralWidget)
self.label_1.setGeometry(QtCore.QRect(390, 100, 111, 17))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_1.setFont(font)
self.label_1.setObjectName(_fromUtf8("label_1"))
self.dial_2 = QtGui.QDial(self.centralWidget)
self.dial_2.setGeometry(QtCore.QRect(390, 120, 101, 91))
self.dial_2.setFocusPolicy(QtCore.Qt.ClickFocus)
self.dial_2.setNotchesVisible(True)
self.dial_2.setObjectName(_fromUtf8("dial_2"))
self.label_2 = QtGui.QLabel(self.centralWidget)
self.label_2.setGeometry(QtCore.QRect(390, 210, 111, 17))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.lcdNumber_2 = QtGui.QLCDNumber(self.centralWidget)
self.lcdNumber_2.setEnabled(True)
self.lcdNumber_2.setGeometry(QtCore.QRect(500, 150, 81, 41))
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(True)
font.setWeight(75)
self.lcdNumber_2.setFont(font)
self.lcdNumber_2.setFrameShape(QtGui.QFrame.Panel)
self.lcdNumber_2.setFrameShadow(QtGui.QFrame.Raised)
self.lcdNumber_2.setLineWidth(2)
self.lcdNumber_2.setMidLineWidth(0)
self.lcdNumber_2.setDigitCount(4)
self.lcdNumber_2.setMode(QtGui.QLCDNumber.Dec)
self.lcdNumber_2.setSegmentStyle(QtGui.QLCDNumber.Flat)
self.lcdNumber_2.setObjectName(_fromUtf8("lcdNumber_2"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 611, 25))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.dial_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.lcdNumber_1.display)
QtCore.QObject.connect(self.dial_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.lcdNumber_2.display)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.label_1.setText(_translate("MainWindow", "Linear Velocity", None))
self.label_2.setText(_translate("MainWindow", "Angular Velocity", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You can connect own function which gets value and use print() to display it
QtCore.QObject.connect(self.dial_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.lcdNumber_1.display)
# connect own function
QtCore.QObject.connect(self.dial_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.my_function)
def my_function(self, value):
print(value)
The same with second QDial.
You can even use directly print without creating own function because print will gets value.
QtCore.QObject.connect(self.dial_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), print)
EDIT: as #musicamante mentioned in comment - this version
SIGNAL(..., print)
will work only in Python 3 because print in Python 2 is not function.
Or you will have to use in Python 2
from __future__ import print_function

how to connect two windows in pyqt4?

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(833, 592)
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(5, 9, 1366, 700))
self.label.setText(_fromUtf8(""))
self.label.setPixmap(QtGui.QPixmap(_fromUtf8("H:/Community/images/Library-Books2.jpg")))
self.label.setScaledContents(True)
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(40, 90, 91, 31))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Plantagenet Cherokee"))
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.lineEdit = QtGui.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(160, 90, 361, 31))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(9)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(540, 92, 51, 31))
self.pushButton.setText(_fromUtf8(""))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("H:/Community/community/Library/build/classes/library/search.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton.setIcon(icon)
self.pushButton.setFlat(False)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.plainTextEdit = QtGui.QPlainTextEdit(Dialog)
self.plainTextEdit.setGeometry(QtCore.QRect(10, 140, 900, 391))
self.plainTextEdit.setBackgroundVisible(False)
self.plainTextEdit.setCenterOnScroll(False)
self.plainTextEdit.setObjectName(_fromUtf8("plainTextEdit"))
self.pushButton_2 = QtGui.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(410, 540, 90, 50))
self.pushButton_2.setText(_fromUtf8(""))
self.connect(self.pushButton, QtCore.SIGNAL('clicked()'), self.open)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("H:/Community/images/new-button3 - Copy.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton_2.setIcon(icon1)
self.pushButton_2.setIconSize(QtCore.QSize(80, 80))
self.pushButton_2.setFlat(True)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def open(self):
fileName = QtGui.QFileDialog.getOpenFileName(self, 'OpenFile')
self.LineEdit.setText(fileName)
print(fileName)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label_2.setText(_translate("Dialog", "FileName", None))
Generally when I have windows working together I will set one as the others parent or have methods for one that receives data from the other. For example:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.setupUi(self)
self.run_btn.clicked.connect(self.setup_project)
def setup_project(self):
self.project = ProjectParams(parent=self)
self.project.show()
if self.project.exec_() == QtWidgets.QDialog.Accepted:
self.params = self.project.params
self.loops = self.project.loops
class ProjectParams(QtWidgets.QDialog, Ui_ProjectParams):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent=parent)
self.setupUi(self)
self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
self.params = {}
From your error I would think you need to change:
self.connect(self.pushButton, QtCore.SIGNAL('clicked()'), self.open)
to:
self.pushButton.clicked.connect(self.open)

issue with ScrollArea in Pyqt using QtDesigner

I designed a window with QtDesigner and added a scrollarea and a layout in it, but the scroll area doesn't scroll, it shows the scroll bar but It cant be scrolled at all.
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 StartQT4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(767, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(230, 300, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.lineEdit = QtGui.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(80, 330, 371, 71))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 767, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(130, 70, 301, 191))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setMinimumSize(QtCore.QSize(100, 100))
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 299, 189))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(100, 100))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.horizontalLayoutWidget = QtGui.QWidget(self.scrollAreaWidgetContents)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(-1, -1, 301, 191))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout = QtGui.QVBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
p= QtGui.QPalette()
p.setColor(QtGui.QPalette.Background, QtCore.Qt.white)
self.scrollArea.setAutoFillBackground(True)
self.scrollArea.setPalette(p)
self.retranslateUi(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "send", None))
I want to add labels and this is how I do it
from main_ui import *
import sys
global height
height=10
def send():
global height
label=QtGui.QLabel(myapp.ui.horizontalLayoutWidget)
label.setGeometry(QtCore.QRect(10, height, 46, 13))
height=height+label.height()
label.setText(myapp.ui.lineEdit.text())
label.show()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
QtCore.QObject.connect(myapp.ui.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), send)
myapp.setCentralWidget(myapp.ui.centralwidget)
QtCore.QMetaObject.connectSlotsByName(myapp)
sys.exit(app.exec_())
Sir, your code is a bit messed.
Here is a small example, see if it works. There is no secret. :D
it's in PyQt5. You just gotta change your imports to PyQt4.
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QScrollArea
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
class WSlideBar(QWidget):
"""WSlideBar is a personalized slide bar."""
w_container = None
v_layout_container = None
v_scroll_area = None
v_layout_preview = None
def __init__(self):
"""Init UI."""
super(WSlideBar, self).__init__()
self.init_ui()
def init_ui(self):
"""Init all ui object requirements."""
self.setFixedSize(100,500)
self.setStyleSheet("""
background: gray;
""")
# Container Widget
self.w_container = QWidget()
self.w_container.setFixedWidth(100)
# Layout of Container Widget
self.v_layout_container = QVBoxLayout()
self.v_layout_container.setSpacing(100)
aux = QWidget()
aux.setFixedSize(10,10)
aux.setStyleSheet("""background: red;""")
aux2 = QWidget()
aux2.setFixedSize(20, 20)
aux2.setStyleSheet("""background: blue;""")
aux3 = QWidget()
aux3.setFixedSize(15, 15)
aux3.setStyleSheet("""background: yellow;""")
aux4 = QWidget()
aux4.setFixedSize(50,50)
aux4.setStyleSheet("""background: rgb(0,255,0,30%);""")
aux5 = QWidget()
aux5.setFixedSize(40, 40)
aux5.setStyleSheet("""background: green;""")
aux6 = QWidget()
aux6.setFixedSize(40, 40)
aux6.setStyleSheet("""background: green;""")
self.v_layout_container.addWidget(aux)
self.v_layout_container.addWidget(aux2)
self.v_layout_container.addWidget(aux3)
self.v_layout_container.addWidget(aux4)
self.v_layout_container.addWidget(aux5)
self.v_layout_container.addWidget(aux6)
self.w_container.setLayout(self.v_layout_container)
self.v_scroll_area = QScrollArea(self)
self.v_scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.v_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.v_scroll_area.setWidget(self.w_container)
# Scroll Area Layer add
self.v_layout_preview = QVBoxLayout()
self.setLayout(self.v_layout_preview)
self.v_layout_preview.addWidget(self.v_scroll_area)
def run():
app = QApplication(sys.argv)
GUI = WSlideBar()
GUI.show()
sys.exit(app.exec_())
run()
OBS: You will just have to change for QPushButtons, QLabels,... instead of small QWidgets and whatever you need.

AttributeError: 'dataAcquisition' object has no attribute 'gpioButton'

I'm trying to connect a push-button on my main window to open a new widget when I click it. But each time I run the program I get this error:
AttributeError: 'dataAcquisition' object has no attribute 'gpioButton'
I will be grateful if someone can help.
Here's my code:
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
from gpiodialog import Ui_GPIODialog
import sys
class gpioDialog(QtGui.QDialog, Ui_GPIODialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
flags = QtCore.Qt.Drawer | QtCore.Qt.WindowStaysOnTopHint
self.setWidowFlags(flags)
self.ui = Ui_GPIODialog
self.ui.setupUi(self)
self.gpioOKButton.clicked.connect(self.acceptOKButtonClicked)
def acceptOKButtonClicked(self):
self.close()
class dataAcquisition(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.gpioButton.clicked.connect(self.gpioButton_clicked)
self.popGPIO = gpioDialog()
def gpioButton_clicked(self):
self.popGPIO.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
MainWindow = dataAcquisition()
MainWindow.show()
sys.exit(app.exec_())
mainwindow.py code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Tue Oct 18 02:57:57 2016
# by: PyQt4 UI code generator 4.11.2
#
# 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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(700, 600)
MainWindow.setMinimumSize(QtCore.QSize(700, 600))
MainWindow.setMaximumSize(QtCore.QSize(700, 600))
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gpioButton = QtGui.QToolButton(self.centralwidget)
self.gpioButton.setGeometry(QtCore.QRect(20, 80, 181, 61))
self.gpioButton.setObjectName(_fromUtf8("gpioButton"))
self.procButton = QtGui.QPushButton(self.centralwidget)
self.procButton.setGeometry(QtCore.QRect(20, 180, 181, 61))
self.procButton.setObjectName(_fromUtf8("procButton"))
self.startButton = QtGui.QPushButton(self.centralwidget)
self.startButton.setEnabled(True)
self.startButton.setGeometry(QtCore.QRect(20, 360, 131, 51))
self.startButton.setObjectName(_fromUtf8("startButton"))
self.stopButton = QtGui.QPushButton(self.centralwidget)
self.stopButton.setGeometry(QtCore.QRect(190, 360, 131, 51))
self.stopButton.setObjectName(_fromUtf8("stopButton"))
self.plotButton = QtGui.QPushButton(self.centralwidget)
self.plotButton.setGeometry(QtCore.QRect(20, 460, 181, 61))
self.plotButton.setObjectName(_fromUtf8("plotButton"))
self.columnView = QtGui.QColumnView(self.centralwidget)
self.columnView.setGeometry(QtCore.QRect(340, 50, 341, 251))
self.columnView.setObjectName(_fromUtf8("columnView"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(280, 20, 221, 21))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.saveButton = QtGui.QPushButton(self.centralwidget)
self.saveButton.setEnabled(True)
self.saveButton.setGeometry(QtCore.QRect(410, 420, 211, 31))
self.saveButton.setObjectName(_fromUtf8("saveButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 700, 27))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.gpioButton.setText(_translate("MainWindow", "GPIO Number of inputs", None))
self.procButton.setText(_translate("MainWindow", "Processing", None))
self.startButton.setText(_translate("MainWindow", "Start Acquiring", None))
self.stopButton.setText(_translate("MainWindow", "Stop Acquiring", None))
self.plotButton.setText(_translate("MainWindow", "Start Live Plot", None))
self.label_2.setText(_translate("MainWindow", "Data Acquisition System", None))
self.saveButton.setText(_translate("MainWindow", "Save this session\'s data", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
gpiodialog.py code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gpiodialog.ui'
#
# Created: Tue Oct 18 03:11:51 2016
# by: PyQt4 UI code generator 4.11.2
#
# 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_GPIODialog(object):
def setupUi(self, GPIODialog):
GPIODialog.setObjectName(_fromUtf8("GPIODialog"))
GPIODialog.resize(400, 300)
self.gpioOKButton = QtGui.QPushButton(GPIODialog)
self.gpioOKButton.setGeometry(QtCore.QRect(170, 240, 101, 31))
self.gpioOKButton.setObjectName(_fromUtf8("gpioOKButton"))
self.label = QtGui.QLabel(GPIODialog)
self.label.setGeometry(QtCore.QRect(90, 20, 191, 21))
font = QtGui.QFont()
font.setPointSize(13)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.retranslateUi(GPIODialog)
QtCore.QMetaObject.connectSlotsByName(GPIODialog)
def retranslateUi(self, GPIODialog):
GPIODialog.setWindowTitle(_translate("GPIODialog", "Dialog", None))
self.gpioOKButton.setText(_translate("GPIODialog", "OK", None))
self.label.setText(_translate("GPIODialog", "Choose GPIO input bins", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
GPIODialog = QtGui.QDialog()
ui = Ui_GPIODialog()
ui.setupUi(GPIODialog)
GPIODialog.show()
sys.exit(app.exec_())
You created a separate namespace for the ui, so you would need to access the button like this:
self.ui.gpioButton.clicked.connect(self.gpioButton_clicked)
However, if you'd prefer to have all the widgets as attributes of the window, do this:
class gpioDialog(QtGui.QDialog, Ui_GPIODialog):
def __init__(self, parent=None):
super(gpioDialog, self).__init__(parent)
flags = QtCore.Qt.Drawer | QtCore.Qt.WindowStaysOnTopHint
self.setWindowFlags(flags)
self.setupUi(self)
self.gpioOKButton.clicked.connect(self.acceptOKButtonClicked)
class dataAcquisition(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(dataAcquisition, self).__init__(parent)
self.setupUi(self)
self.gpioButton.clicked.connect(self.gpioButton_clicked)
self.popGPIO = gpioDialog()

Qt/PyQt GraphicView

I am trying to recreate some pyqt codes using qt designer.I generated a simple python code using pyuic4.The image should load only in the QgraphicView area but it covers the entire window and I could not see the push buttons.
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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(608, 526)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(300, 20, 258, 244))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout = QtGui.QVBoxLayout(self.widget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.graphicsView = QtGui.QGraphicsView(self.widget)
self.graphicsView.setEnabled(True)
self.graphicsView.setMinimumSize(QtCore.QSize(200, 200))
self.graphicsView.setMaximumSize(QtCore.QSize(400, 400))
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.verticalLayout.addWidget(self.graphicsView)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtGui.QPushButton(self.widget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.horizontalLayout.addWidget(self.pushButton_2)
self.verticalLayout.addLayout(self.horizontalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 608, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "PushButton", None))
self.pushButton_2.setText(_translate("MainWindow", "PushButton", None))
and the main file is :
import sys
from PyQt4 import QtCore, QtGui
from graphics_test_output import Ui_MainWindow
class Main(QtGui.QMainWindow,Ui_MainWindow):
def __init__(self):
super(Main,self).__init__()
self.setupUi(self)
self.mw = MainWidget()
self.setCentralWidget(self.mw)
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWidget,self).__init__(parent)
self.scene = QtGui.QGraphicsScene()
self.view = QtGui.QGraphicsView(self.scene)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.view)
self.setLayout(layout)
self.pixmap_item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap('Image.png'), None, self.scene)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
I have added screenshots of ui design and the current output and they would appear.
ui_design:
current_output:

Categories

Resources