Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #tableview pyside+linux(ubuntu) graphics bug (pyside+windows and pyqt4 good)
- # update: fixed 1.1.2 version
- import sys
- import os
- import re
- from PySide.QtGui import *
- from PySide.QtCore import *
- from PySide.QtSql import *
- #from PyQt4.QtGui import *
- #from PyQt4.QtCore import *
- #from PyQt4.QtSql import *
- #static dataset
- from collections import namedtuple
- # sqltables def
- tablefield=namedtuple('tablefield', 'fieldname properties foreignkey')
- DBTABLES={
- 'szl':[
- tablefield('id','INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',''),
- tablefield('counter','INTEGER',''),
- tablefield('cname','VARCHAR(180)',''),
- tablefield('city','VARCHAR(80)',''),
- tablefield('street','VARCHAR(80)',''),
- tablefield('footer','TEXT','')
- ],
- 'ttl':[
- tablefield('id','INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL',''),
- tablefield('code','VARCHAR(20)',''),
- tablefield('taxcode','VARCHAR(20)',''),
- tablefield('iname','VARCHAR(250)',''),
- tablefield('amount','REAL(14,4)',''),
- tablefield('netto','REAL(14,4)',''),
- tablefield('taxvalue','REAL(14,4)',''),
- tablefield('brutto','REAL(14,4)','')
- ]}
- # subgrids def
- gridobj=namedtuple('gridobj', 'gridname grouplabel posx posy width height rowstretch columnstretch')
- GRIDLIST={
- 'szl':[
- gridobj('gl1','szl valami',0,0,1,1,0,0),
- ],
- 'ttl':[
- gridobj('gl2','tableview ',0,0,1,1,0,0),
- gridobj('gl1','fields',1,0,1,1,0,0)
- ]}
- #labels text and input object other text
- scrobjtext=namedtuple('scrobjtext', 'labeltext statustext whatstext tooltiptext columntext')
- SCRTEXTLIST={
- 'counter':scrobjtext('counter:','','','',''),
- 'cname':scrobjtext('Name:','','','',''),
- 'city':scrobjtext('Cityname:','','','',''),
- 'street':scrobjtext('Street:','','','',''),
- 'footer':scrobjtext('footer','','','',''),
- 'code':scrobjtext('Code: ','','','',''),
- 'taxcode':scrobjtext('Taxcode:','','','',''),
- 'iname':scrobjtext('Name: ','','','',''),
- 'amount':scrobjtext('Amount:','','','',''),
- 'netto':scrobjtext('Netto:','','','',''),
- 'taxvalue':scrobjtext('Taxvalue','','','',''),
- 'brutto':scrobjtext('Brutto','','','','')
- }
- # screen input widgets def and pos and other
- scrobj=namedtuple('scrobj','gridname labelfixedwidth inputfixedwidth inputposx inputposy inputwidth inputheight inputobjname')
- #(gridname:[inputobj])
- SCRLIST={
- 'szl':[
- scrobj('gl1',100,300,0,1,1,1,'counterMyLineEdit'),
- scrobj('gl1',0,0,1,1,1,1,'cnameMyLineEdit'),
- scrobj('gl1',0,0,2,1,1,1,'cityMyLineEdit'),
- scrobj('gl1',0,0,3,1,1,1,'streetMyLineEdit'),
- scrobj('gl1',0,0,4,1,1,1,'valutipusMyComboBox'),
- scrobj('gl1',0,0,5,1,1,1,'footerMyTextEdit')
- ],
- 'ttl':[
- scrobj('gl1',100,300,0,1,1,1,'codeMyLineEdit'),
- scrobj('gl1',0,0,1,1,1,1,'taxcodeMyLineEdit'),
- scrobj('gl1',0,0,2,1,1,1,'inameMyLineEdit'),
- scrobj('gl1',0,0,3,1,1,1,'amountMyDoubleSpinBox'),
- scrobj('gl1',0,0,4,1,1,1,'nettoMyDoubleSpinBox'),
- scrobj('gl1',0,0,5,1,1,1,'taxvalueMyDoubleSpinBox'),
- scrobj('gl1',0,0,6,1,1,1,'bruttoMyDoubleSpinBox')
- ]}
- # tables (gridname:[tables])
- TABLELIST={
- 'ttl':[
- scrobj('gl2',0,0,0,0,1,2,'Say_ttlMyTableView')
- ]
- }
- # screen tableviews def
- tablecol=namedtuple('tablecol','fieldname width')
- # (TABLELIST.inputobjname:[])
- SCRTABLE={
- 'Say_ttlMyTableView':[
- tablecol('codeMyLineEdit',100),
- tablecol('inameMyLineEdit',390),
- tablecol('amountMyDoubleSpinBox',100),
- tablecol('nettoMyDoubleSpinBox',100),
- tablecol('bruttoMyDoubleSpinBox',100)
- ]
- }
- # buttons def (gridname:[buttons])
- BUTTONLIST={
- 'ttl':[
- ['firstButton','First',':/first.png','self.firstRecord'],
- ['prevButton','Previous',':/prev.png','self.prevRecord'],
- ['nextButton','Next',':/next.png','self.nextRecord'],
- ['lastButton','Last',':/first.png','self.lastRecord'],
- ['newButton','New',':/add.png','self.newRecord'],
- ['deleteButton','Delete',':/delete.png','self.deleteRecord'],
- ['saveButton','Save',':/save.png','self.saveRecord'],
- ['cancelButton','Cancel',':/save.png','self.cancelRecord']
- ]}
- class MyDoubleSpinBox(QDoubleSpinBox):
- def __init__(self):
- super(MyDoubleSpinBox,self).__init__()
- self.setDecimals(2)
- self.setMinimum(0.00)
- self.setMaximum(99999999999.99)
- self.setAlignment(Qt.AlignRight)
- class MyLabel(QLabel):
- def __init__(self):
- super(MyLabel,self).__init__()
- self.setFont(labelfont)
- class MyLineEdit(QLineEdit):
- def __init__(self):
- super(MyLineEdit,self).__init__()
- class MyTextEdit(QTextEdit):
- def __init__(self):
- super(MyTextEdit,self).__init__()
- class MyGridLayout(QGridLayout):
- def __init__(self):
- super(MyGridLayout,self).__init__()
- self.setVerticalSpacing(3)
- self.setHorizontalSpacing(3)
- class ItemFormatDelegate1(QSqlRelationalDelegate):
- def __init__(self, parent=None):
- super(ItemFormatDelegate1, self).__init__(parent)
- def paint(self, painter, option, index):
- myoption = QStyleOptionViewItem(option)
- value=index.data(Qt.DisplayRole)
- if type(value)==int:
- myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
- elif type(value)==float:
- myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
- elif type(value)==str:
- myoption.displayAlignment |= Qt.AlignLeft|Qt.AlignVCenter
- else:
- myoption.displayAlignment |= Qt.AlignCenter|Qt.AlignVCenter
- QSqlRelationalDelegate.paint(self, painter, myoption, index)
- class ItemFormatDelegate(QSqlRelationalDelegate):
- def __init__(self, parent=None):
- super(ItemFormatDelegate, self).__init__(parent)
- def paint(self, painter, option, index):
- value=index.data(Qt.DisplayRole)
- if type(value)==int:
- valuealign=Qt.AlignRight|Qt.AlignVCenter
- valueout = '{0:}'.format(value)
- elif type(value)==float:
- valuealign=Qt.AlignRight|Qt.AlignVCenter
- valueout = '{0:.2f}'.format(value)
- elif type(value)==str:
- valuealign=Qt.AlignLeft|Qt.AlignVCenter
- valueout = '{}'.format(value)
- else:
- valuealign=Qt.AlignCenter|Qt.AlignVCenter
- valueout = '{}'.format(value)
- painter.drawText(option.rect,valuealign, valueout)
- class MyFrame(QFrame):
- ''' screen factory :frame->gridlayout->groupbox->subgridlayout->qwidgets
- data factory: temptable->QSqlTableModel->QDataWidgetMapper->QTableView
- NAMEDTUPLES:
- subgridlayouts def: GRIDLIST [(gridname, grouplabel, posx, posy, width, height, rowstretch, columnstretch)]
- qwidget input def: SCRLIST [(gridname, labelfixedwidth, inputfixedwidth, inputposx, inputposy, inputwidth, inputheight, inputobjname)]
- qwidget input def texts: SCRTEXTLIST [(labeltext, statustext, whatstext, tooltiptext, columntext)]
- database sql def: DBTABLES [(fieldname, properties)]
- tableview def: SCRTABLE [(fieldname, width)]'''
- def __init__(self,framename):
- super(MyFrame, self).__init__()
- self.framename=framename
- self.inputlist=[]
- self.tablecolumn=[]
- self.gridLayout = MyGridLayout()
- self.gridLayout.setVerticalSpacing(10)
- self.gridLayout.setHorizontalSpacing(10)
- self.createSubgrids()
- self.fields()
- self.addSubgrids()
- self.buttons()
- self.createTmptable()
- self.mapping()
- self.tableViews()
- self.setLayout(self.gridLayout)
- def createSubgrids(self):
- try:
- for grid in GRIDLIST[self.framename]:
- self.__dict__[grid.gridname]=MyGridLayout()
- except:pass
- def addSubgrids(self):
- '''subgrids to groupbox to gridLayout'''
- try:
- for grid in GRIDLIST[self.framename]:
- self.__dict__[grid.gridname].setVerticalSpacing(3)
- self.__dict__[grid.gridname].setHorizontalSpacing(3)
- self.__dict__[grid.gridname].setColumnStretch(grid.columnstretch,1)
- self.__dict__[grid.gridname].setRowStretch(grid.rowstretch,1)
- self.__dict__[grid.gridname+'groupbox']=QGroupBox()
- self.__dict__[grid.gridname+'groupbox'].setFont(groupfont)
- self.__dict__[grid.gridname+'groupbox'].setTitle(grid.grouplabel)
- self.__dict__[grid.gridname+'groupbox'].setLayout(self.__dict__[grid.gridname])
- self.gridLayout.addWidget(self.__dict__[grid.gridname+'groupbox'],grid.posx,grid.posy,grid.width,grid.height)
- except:pass
- def fields(self):
- '''labels and inputs (lineedit,spinbox...etc)'''
- try:
- for obj in SCRLIST[self.framename]:
- objdef=re.split('My',obj.inputobjname)
- objnamekey=objdef[0]
- objclass=objdef[1]
- if not objclass.endswith('Label'):
- self.__dict__[obj.inputobjname]=eval('My'+objclass+'()')
- self.__dict__[obj.inputobjname].setFont(inputfont)
- if obj.inputfixedwidth:
- self.__dict__[obj.inputobjname].setFixedWidth(obj.inputfixedwidth)
- self.__dict__[obj.gridname].addWidget(self.__dict__[obj.inputobjname],obj.inputposx,obj.inputposy,obj.inputwidth,obj.inputheight)
- self.inputlist.append('self.'+obj.inputobjname) #(to datawidgetmapper)
- self.tablecolumn.append(objnamekey) #(to model and temptable)
- if SCRTEXTLIST[objnamekey].labeltext:
- labelobjname=objnamekey+'MyLabel'
- self.__dict__[labelobjname]=MyLabel()
- self.__dict__[labelobjname].setText(SCRTEXTLIST[objnamekey].labeltext)
- if obj.labelfixedwidth:
- self.__dict__[labelobjname].setFixedWidth(obj.labelfixedwidth)
- if obj.inputobjname:
- self.__dict__[labelobjname].setBuddy(self.__dict__[obj.inputobjname])
- self.__dict__[obj.gridname].addWidget(self.__dict__[labelobjname],obj.inputposx,obj.inputposy-1,1,1)
- except:pass
- def buttons(self):
- try:
- self.buttonLayout = QHBoxLayout()
- for buttonname,buttontext,buttonicon,buttonfunction in BUTTONLIST[self.framename]:
- self.__dict__[buttonname] = QPushButton()
- self.__dict__[buttonname].setText(buttontext)
- self.__dict__[buttonname].setIcon(QIcon(buttonicon))
- self.buttonLayout.addWidget(self.__dict__[buttonname])
- self.connect(self.__dict__[buttonname], SIGNAL("clicked()"),eval(buttonfunction))
- self.gridLayout.addLayout(self.buttonLayout, 4, 0, 1, self.gridLayout.columnCount())
- except:
- self.buttonLayout=None
- def createTmptable(self):
- if self.tablecolumn and not self.framename+'tmp' in db.tables():
- fieldsqldef=[]
- for field in self.tablecolumn:
- for dbtable in DBTABLES.keys():
- for dbfield in DBTABLES[dbtable]:
- if dbfield.fieldname==field:
- fieldsqldef.append((dbfield.fieldname,dbfield.properties))
- field=''
- exit
- if not field:
- exit
- cur=QSqlQuery()
- cur.exec_('CREATE TABLE {0} ( {1} ) '.format(self.framename+'tmp',
- ', '.join(fieldname+' '+properties for fieldname,properties in fieldsqldef)))
- def mapping(self):
- try:
- self.model = QSqlTableModel(self)
- self.model.setTable(self.framename+'tmp')
- self.model.select()
- for index,columnname in enumerate(self.tablecolumn):
- self.model.setHeaderData(index,Qt.Horizontal,SCRTEXTLIST[columnname].columntext
- if SCRTEXTLIST[columnname].columntext else SCRTEXTLIST[columnname].labeltext )
- self.mapper = QDataWidgetMapper(self)
- self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
- self.mapper.setModel(self.model)
- for index,inputobj in enumerate(self.inputlist):
- self.mapper.addMapping(eval(inputobj),index)
- self.mapper.toFirst()
- except:
- self.model=None
- self.mapper=None
- def tableViews(self):
- try:
- for obj in TABLELIST[self.framename]:
- counter=0
- self.tableview=obj.inputobjname
- self.__dict__[obj.inputobjname]=QTableView()
- self.__dict__[obj.inputobjname].setModel(self.model)
- self.items=ItemFormatDelegate(self)
- self.__dict__[obj.inputobjname].setItemDelegate(self.items)
- self.__dict__[obj.inputobjname].setFont(inputfont)
- self.__dict__[obj.inputobjname].setEditTriggers(QAbstractItemView.NoEditTriggers)
- self.__dict__[obj.inputobjname].setSelectionBehavior(QAbstractItemView.SelectRows)
- self.__dict__[obj.inputobjname].setSelectionMode(QTableView.SingleSelection)
- self.__dict__[obj.inputobjname].horizontalHeader().setStretchLastSection(True)
- for index,inputfield in enumerate(self.inputlist):
- if re.split('\.',inputfield)[1] in [col.fieldname for col in SCRTABLE[obj.inputobjname]]:
- self.__dict__[obj.inputobjname].setColumnWidth(index,SCRTABLE[obj.inputobjname][counter].width)
- counter+=1
- else:
- self.__dict__[obj.inputobjname].setColumnHidden(index, True)
- self.__dict__[obj.gridname].addWidget(self.__dict__[obj.inputobjname],obj.inputposx,obj.inputposy,obj.inputwidth,obj.inputheight)
- self.__dict__[obj.gridname].setRowMinimumHeight(0,600)
- self.connect(self.__dict__[obj.inputobjname],SIGNAL('clicked(QModelIndex)'),
- lambda x:self.mapper.setCurrentModelIndex(self.__dict__[obj.inputobjname].selectedIndexes()[0]))
- self.tableSelectRow()
- except:pass
- def tableSelectRow(self):
- row = self.mapper.currentIndex()
- eval(self.inputlist[0]).setFocus()
- if self.tableview:
- #self.__dict__[self.tableview].update()
- self.__dict__[self.tableview].selectRow(row)
- def firstRecord(self):
- self.mapper.toFirst()
- self.tableSelectRow()
- def prevRecord(self):
- self.mapper.toPrevious()
- self.tableSelectRow()
- def nextRecord(self):
- self.mapper.toNext()
- self.tableSelectRow()
- def lastRecord(self):
- self.mapper.toLast()
- self.tableSelectRow()
- def newRecord(self):
- row = self.model.rowCount()
- self.model.insertRow(row)
- #self.model.submitAll()
- self.deleteInputObjectValue()
- self.lastRecord()
- def deleteRecord(self):
- if (QMessageBox.question(self,"Delete","Delete ?",QMessageBox.Yes|QMessageBox.No)==QMessageBox.No):
- return
- row = self.mapper.currentIndex()
- self.model.removeRow(row)
- self.model.submitAll()
- if row + 1 >= self.model.rowCount():
- row-=1
- self.mapper.setCurrentIndex(row)
- self.tableSelectRow()
- def saveRecord(self):
- row = self.mapper.currentIndex()
- self.mapper.submit()
- #self.model.submitAll()
- self.mapper.setCurrentIndex(row)
- self.tableSelectRow()
- def cancelRecord(self):
- self.mapper.revert()
- self.tableSelectRow()
- def deleteInputObjectValue(self):
- for key in self.__dict__.keys():
- if not key.startswith('Say_'):
- if re.search('MyDoubleSpinBox',key):
- self.__dict__[key].setValue(0)
- if re.search('MyLineEdit',key):
- self.__dict__[key].setText('')
- if re.search('MyTextEdit',key):
- self.__dict__[key].clear()
- if re.search('MyComboBox',key):
- self.__dict__[key].setCurrentIndex(0)
- class PageOne(MyFrame):
- def __init__(self):
- super(PageOne,self).__init__('szl')
- self.gridLayout.setColumnStretch(3,1)
- self.gridLayout.setRowStretch(10,1)
- def megnincs(self):pass
- class PageTwo(MyFrame):
- def __init__(self):
- super(PageTwo,self).__init__('ttl')
- self.gridLayout.setRowStretch(11,1)
- class MainWindow(QMainWindow):
- def __init__(self,window):
- super(MainWindow, self).__init__()
- window.resize(940,680)
- self.tabwidget = QTabWidget(window)
- self.tabwidget.setGeometry(QRect(10, 10, 920, 660))
- self.szla()
- window.show()
- def szla(self):
- self.tab2=QTabWidget()
- self.tabwidget.addTab(self.tab2,'szlprobe')
- self.szlframe=PageOne()
- self.tab2.addTab(self.szlframe,'Szlpage')
- self.ttlframe=PageTwo()
- self.tab2.addTab(self.ttlframe,'Ttlpage')
- def createTables():
- for tablanev in DBTABLES.keys():
- createTable(tablanev)
- def createTable(tablanev):
- cur=QSqlQuery()
- cur.exec_('CREATE TABLE {0} ( {1} ) '.format(tablanev,createTableDef(tablanev)))
- def createTableDef(tablanev):
- return (', '.join(fieldname+' '+properties for fieldname,properties,foreign in DBTABLES[tablanev]))
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- app.setStyle('plastique') #windowsvista,cleanlooks,windows”, “motif”, “cde”, “plastique”, “windowsxp”, or “macintosh”.
- betu=QFont('Arial')
- betu.setPointSize(11)
- betu.setBold(True)
- app.setFont(betu)
- inputfont=betu
- labelfont=QFont('Arial')
- labelfont.setPointSize(11)
- labelfont.setBold(False)
- groupfont=QFont('Arial')
- groupfont.setPointSize(9)
- groupfont.setBold(True)
- filename = os.path.join(os.path.dirname(__file__), "probe.db")
- create = not QFile.exists(filename)
- db = QSqlDatabase.addDatabase("QSQLITE")
- db.setDatabaseName(filename)
- if not db.open():
- QMessageBox.warning(None, "bugreport","Database error {}".format(db.lastError().text()))
- sys.exit(1)
- if create:
- createTables()
- window=QMainWindow()
- mainwindow = MainWindow(window)
- sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement