Code refactoring

This commit is contained in:
Sergey Kalinin 2017-03-21 16:47:18 +03:00
parent 35093c29f5
commit f43e23ee6a
2 changed files with 176 additions and 284 deletions

4
dm.py
View File

@ -134,7 +134,7 @@ def createTables(tbl_list):
i = i + 1
tbl_descr_list.append(one_Table_descr)
tbl_struct_list.append(one_Table_struct)
print(qwery_create)
#print(qwery_create)
#c.execute(qwery_create)
return tbl_names_list
@ -180,7 +180,7 @@ def selectData(tbl):
subqwery = "(SELECT (" + field_replace + ") FROM " + subqwery +" WHERE "+ table1 + "." + field1 +"="+ tbl +"."+ field +") AS " + field
qwery = qwery.replace(field, subqwery)
qwery = qwery.rstrip(',') + " FROM " + tbl + " LIMIT 10000"
print(qwery)
#print(qwery)
c.execute(qwery)
return c.fetchall()

456
gui.py
View File

@ -2,124 +2,16 @@
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
#import pymysql
import dm
# conn = pymysql.connect(
# db='ats',
# user='dba',
# passwd='AlsprofilinE',
# host='kis',
# charset='utf8')
# c = conn.cursor()
class MainWin(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
#заглушка
def addNewRecord(self):
editForm = EditForm()
editForm.setParent(self)
editForm.show()
#tablesDataWidget.setCellWidget(0, 0, edit)
#callEdit = tablesDataWidget.cellWidget(0, 0)
#callEdit.text()
def initUI(self):
textEdit = QTextEdit()
splitter = WorkArea()
self.setCentralWidget(splitter)
#self.setCentralWidget(textEdit)
newAction = QAction(QIcon('img/new.gif'), 'Добавить', self)
newAction.setShortcut('Ins')
newAction.setStatusTip('Добавить')
newAction.triggered.connect(self.addNewRecord)
deleteAction = QAction(QIcon('img/delete.gif'), 'Удалить', self)
deleteAction.setShortcut('Del')
deleteAction.setStatusTip('Удалить')
#deleteAction.triggered.connect(self.qqqq)
exitAction = QAction(QIcon('img/exit.gif'), 'Выход', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Выход')
exitAction.triggered.connect(self.close)
cutAction = QAction(QIcon('img/cut.gif'), 'Вырезать', self)
cutAction.setShortcut('Ctrl+X')
cutAction.setStatusTip('Вырезать')
#cutAction.triggered.connect(self.close)
copyAction = QAction(QIcon('img/copy.gif'), 'Копировать', self)
copyAction.setShortcut('Ctrl+С')
copyAction.setStatusTip('Копировать')
#copyAction.triggered.connect(self.close)
pasteAction = QAction(QIcon('img/paste.gif'), 'Вставить', self)
pasteAction.setShortcut('Ctrl+V')
pasteAction.setStatusTip('Вставить')
#pasteAction.triggered.connect(self.close)
findAction = QAction(QIcon('img/find.gif'), 'Копировать', self)
findAction.setShortcut('Ctrl+F')
findAction.setStatusTip('Искать')
# findAction.triggered.connect(self.close)
printAction = QAction(QIcon('img/print.gif'), 'Печатать', self)
printAction.setShortcut('Ctrl+P')
printAction.setStatusTip('Печатать')
# printAction.triggered.connect(self.close)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&Файл')
fileMenu.addAction(newAction)
fileMenu.addAction(deleteAction)
fileMenu.addAction(printAction)
fileMenu.addAction(exitAction)
editMenu = menubar.addMenu('&Редактирование')
editMenu.addAction(copyAction)
editMenu.addAction(cutAction)
editMenu.addAction(pasteAction)
editMenu.addAction(printAction)
helpMenu = menubar.addMenu('&Помощь')
#toolbar = self.addToolBar('Редактирование')
toolbar = self.addToolBar('Панель инструментов')
toolbar.addAction(newAction)
toolbar.addAction(deleteAction)
toolbar.addAction(copyAction)
toolbar.addAction(cutAction)
toolbar.addAction(pasteAction)
toolbar.addAction(findAction)
toolbar.addAction(printAction)
#toolbar.addAction(exitAction)
self.setGeometry(300, 300, 850, 650)
self.setWindowTitle('Ацкый быдлокод')
self.show()
class MyTable(QTableWidget):
def __init__(self, tbl, thestruct, *args):
def __init__(self, *args):
QTableWidget.__init__(self, *args)
self.data = thestruct
self.setmydata()
self.tbl = tbl
self.resizeColumnsToContents()
self.horizontalHeader().setSortIndicatorShown(True)
self.horizontalHeader().setStretchLastSection(True)
@ -132,25 +24,10 @@ class MyTable(QTableWidget):
self.setWordWrap(True)
self.setSortingEnabled(True)
#print(self.tbl)
n = 0
for item in dm.getTablesStructure(self.tbl):
# установка заголовков столбцов таблицы
self.setHorizontalHeaderItem(n, QTableWidgetItem(item))
n = n+1
# обработка нажатия мышой на таблице
self.doubleClicked.connect(self.on_click)
# self.doubleClicked.connect(self.contextMenuEvent(self.cursor()))
# добавлем кнопку в ячейку
#self.clicked.connect(self.addButtonToCell())
def addButtonToCell(self):
modelIndex = self.currentIndex()
col = modelIndex.column()
row = modelIndex.row()
button = QPushButton('...', self)
self.setCellWidget(row, col + 1, button)
# показ контекстного меню
def contextMenuEvent(self, event):
Rmenu = QMenu(self)
@ -161,178 +38,193 @@ class MyTable(QTableWidget):
if action == delRecord:
row = self.rowAt(event.pos().y())
col = self.columnAt(event.pos().x())
print("row:%d, col:%d" % (row, col))
print("Удаляем row:%d, col:%d" % (row, col))
item = self.item(self.currentIndex().row(), self.currentIndex().column())
print(item.text())
print("Запись" + item.text())
elif action == addRecord:
editForm = EditForm(self.tbl)
editForm.setParent(self)
editForm.show()
print("Добавить запись ")
addNewRecord()
def on_click(self):
print(self.cursor().pos().x())
#self.contextMenuEvent(self.cursor())
for currentQTableWidgetItem in self.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
def setmydata(self):
n = 0
for key in self.data:
m = 0
for item in key:
# преобразуем все типы в строку
newitem = QTableWidgetItem(str(item))
self.setItem(m, n, newitem)
n += 1
m += 1
class WorkArea(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
# список таблиц
listTablesWidget = QListWidget()
listTablesWidget.setFrameShape(QFrame.StyledPanel)
listTablesWidget.setFixedWidth(200)
# таблица для вывода данных
tablesDataWidget = QTableView()
tablesDataWidget.setFrameShape(QFrame.StyledPanel)
splitter1 = QSplitter(Qt.Horizontal)
splitter1.addWidget(listTablesWidget)
splitter1.addWidget(tablesDataWidget)
splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(splitter1)
#splitter1.setSizes([100, 300])
hbox.addWidget(splitter2)
#splitter1.setStretchFactor(1, 0)
#splitter1.sizeHint()
self.setLayout(hbox)
# выводим список таблиц в левом поле
tblList = dm.initDBstructure()
for i in tblList:
listTablesWidget.addItem(i[1])
# заполняем правый список данными из выбранной таблицы
def addData(tbl_descr):
# выбираем название таблицы по описанию
for i in tblList:
if i[1] == tbl_descr:
tbl_name = i[0]
# удаляем предыдущий виджет таблицы
item = splitter1.widget(1)
if item is not None:
item.deleteLater()
data = dm.selectData(tbl_name)
# проверка на наличие записей в таблице
if data:
# количество строк
rows = len(data)
# КОЛИЧЕСТВО КОЛОНОК
cols = len(data[0])
tablesDataWidget = MyTable(tbl_name, data, rows, cols)
tablesDataWidget.setFrameShape(QFrame.StyledPanel)
splitter1.addWidget(tablesDataWidget)
else:
# если данных в БД нет выводим пустую табличку
tablesDataWidget = QTableView()
tablesDataWidget.setFrameShape(QFrame.StyledPanel)
splitter1.addWidget(tablesDataWidget)
# обработка нажатия мышой на списке
#listTablesWidget.itemClicked.connect(lambda: dm.selectData(listTablesWidget.currentItem))
listTablesWidget.itemClicked.connect(lambda: addData(listTablesWidget.model().data(listTablesWidget.currentIndex())))
def onChanged(self, text):
self.lbl.setText(text)
self.lbl.adjustSize()
# Форма для добавления и редактирования
class EditForm(QWidget):
def __init__(self, tbl):
QWidget.__init__(self)
self.tbl = tbl
self.listFields = self.getTableStructure()
#print(listFields)
self.initUI()
self.setWindowFlags(Qt.Dialog)
#print(self.parent)
#self.parent = parent
def initUI(self):
n = 0
itemsCount = len(self.listFields)
grid = QGridLayout()
grid.setSpacing(10)
for item in self.listFields:
print(itemsCount)
grid.addWidget(QLabel(item), n, 0)
grid.addWidget(QLineEdit(), n, 1)
n = n+1
self.setLayout(grid)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Review')
#self.setParent(parent)
#self.show()
def getTableStructure(self):
listFields = []
for item in dm.getTablesStructure(self.tbl):
listFields.append(item)
# установка заголовков столбцов таблицы
#self.setHorizontalHeaderItem(n, QTableWidgetItem(item))
return listFields
def __init__(self):
super().__init__()
l = QVBoxLayout()
b = QPushButton('Добавить без параметра!')
b.clicked.connect(lambda: self.function1())
b2 = QPushButton('Добавить с параметром!')
b2.clicked.connect(lambda: self.function1(args='параметр'))
l.addWidget(b)
l.addWidget(b2)
self.setLayout(l)
self.show()
if __name__ == '__main__':
def addDataIntoTable(tbl_descr, tblDataWidget):
global tblList
# выбираем название таблицы по описанию
for i in tblList:
if i[1] == tbl_descr:
tbl_name = i[0]
#print(tbl_descr)
data = dm.selectData(tbl_name)
#print(data)
fieldNames = dm.getTablesStructure(tbl_name)
# проверка на наличие записей в таблице
if data:
# количество строк
rows = len(data)
# КОЛИЧЕСТВО КОЛОНОК
cols = len(data[0])
else:
rows = 0
cols = len(fieldNames)
n = 0
tblDataWidget.setRowCount(rows)
tblDataWidget.setColumnCount(cols)
for item in fieldNames:
fieldNames = item + ','
# установка заголовков столбцов таблицы
tblDataWidget.setHorizontalHeaderItem(n, QTableWidgetItem(item))
n = n + 1
n = 0
for key in data:
m = 0
for item in key:
# преобразуем все типы в строку
newitem = QTableWidgetItem(str(item))
tblDataWidget.setItem(m, n, newitem)
n += 1
m += 1
def showMenuToolbar(window):
newAction = QAction(QIcon('img/new.gif'), 'Добавить', window)
newAction.setShortcut('Ins')
newAction.setStatusTip('Добавить')
newAction.triggered.connect(addNewRecord)
deleteAction = QAction(QIcon('img/delete.gif'), 'Удалить', window)
deleteAction.setShortcut('Del')
deleteAction.setStatusTip('Удалить')
# deleteAction.triggered.connect(window.qqqq)
exitAction = QAction(QIcon('img/exit.gif'), 'Выход', window)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Выход')
exitAction.triggered.connect(window.close)
cutAction = QAction(QIcon('img/cut.gif'), 'Вырезать', window)
cutAction.setShortcut('Ctrl+X')
cutAction.setStatusTip('Вырезать')
# cutAction.triggered.connect(window.close)
copyAction = QAction(QIcon('img/copy.gif'), 'Копировать', window)
copyAction.setShortcut('Ctrl+С')
copyAction.setStatusTip('Копировать')
# copyAction.triggered.connect(window.close)
pasteAction = QAction(QIcon('img/paste.gif'), 'Вставить', window)
pasteAction.setShortcut('Ctrl+V')
pasteAction.setStatusTip('Вставить')
# pasteAction.triggered.connect(window.close)
findAction = QAction(QIcon('img/find.gif'), 'Копировать', window)
findAction.setShortcut('Ctrl+F')
findAction.setStatusTip('Искать')
# findAction.triggered.connect(window.close)
printAction = QAction(QIcon('img/print.gif'), 'Печатать', window)
printAction.setShortcut('Ctrl+P')
printAction.setStatusTip('Печатать')
# printAction.triggered.connect(window.close)
window.statusBar()
menubar = window.menuBar()
fileMenu = menubar.addMenu('&Файл')
fileMenu.addAction(newAction)
fileMenu.addAction(deleteAction)
fileMenu.addAction(printAction)
fileMenu.addAction(exitAction)
editMenu = menubar.addMenu('&Редактирование')
editMenu.addAction(copyAction)
editMenu.addAction(cutAction)
editMenu.addAction(pasteAction)
editMenu.addAction(printAction)
helpMenu = menubar.addMenu('&Помощь')
# toolbar = window.addToolBar('Редактирование')
toolbar = window.addToolBar('Панель инструментов')
toolbar.addAction(newAction)
toolbar.addAction(deleteAction)
toolbar.addAction(copyAction)
toolbar.addAction(cutAction)
toolbar.addAction(pasteAction)
toolbar.addAction(findAction)
toolbar.addAction(printAction)
# toolbar.addAction(exitAction)
def addNewRecord():
global listTables, tblRelationsData
tblDescr = listTables.model().data(listTables.currentIndex())
for i in tblList:
if i[1] == tblDescr:
tblName = i[0]
print(tblName)
editForm = EditForm()
#editForm.setParent(listTables)
#editForm.show()
#editForm.setParent(tblRelationsData)
#editForm = Example()
def main():
global tblList, listTables, tblRelationsData
app = QApplication(sys.argv)
ex = MainWin()
sys.exit(app.exec_())
mainWin = QMainWindow()
workArea = QWidget()
mainWin.setCentralWidget(workArea)
hbox = QHBoxLayout()
listTables = QListWidget()
listTables.setFrameShape(QFrame.StyledPanel)
listTables.setFixedWidth(200)
#tblData = QTableWidget()
tblData = MyTable()
tblData.setFrameShape(QFrame.StyledPanel)
tblRelationsData = QTableWidget()
tblRelationsData.setFrameShape(QFrame.StyledPanel)
splitter1 = QSplitter(Qt.Horizontal)
splitter1.addWidget(listTables)
splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(tblData)
splitter2.addWidget(tblRelationsData)
splitter1.addWidget(splitter2)
hbox.addWidget(splitter1)
workArea.setLayout(hbox)
showMenuToolbar(mainWin)
listTables.itemClicked.connect(lambda: addDataIntoTable(listTables.model().data(listTables.currentIndex()), tblData))
# выводим список таблиц в левом поле
tblList = dm.initDBstructure()
for i in tblList:
listTables.addItem(i[1])
mainWin.setGeometry(300, 300, 800, 600)
mainWin.setWindowTitle('Data manipulator')
mainWin.show()
# #!/usr/bin/python3
# # -*- coding: utf-8 -*-
#
# import sys
# from PyQt5.QtCore import Qt
# from PyQt5.QtGui import QIcon
# from PyQt5.QtWidgets import *
#
# def main():
# app = QApplication(sys.argv)
# table = QTableWidget()
# tableItem = QTableWidgetItem()
#
# table.setWindowTitle("Set QWidget for Entire QTableWidget Column")
# table.resize(400, 250)
# table.setRowCount(4)
# table.setColumnCount(3)
#
# table.setHorizontalHeaderLabels(("HEADER 1;HEADER 2;HEADER 3;HEADER 4").split(";"))
#
# table.setItem(0, 0, QTableWidgetItem("ITEM 1_1"))
#
# # Add Widget to the rightmost Element of First Row
# table.setItem(0, 2, tableItem)
#
# # Add QPushButton to the rightmost QTableWidgetItem on first row
# table.setCellWidget(0, 2, QPushButton("Cell Widget"));
#
# # Span Right-Most Item of First Row Here
# table.setSpan(0, 2, table.rowCount(), 1);
# table.show()
# return app.exec_()
return app.exec_()
#
#
# if __name__ == '__main__':
# main()
if __name__ == '__main__':
main()