#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * #import pymysql import dm class MyTable(QTableWidget): def __init__(self, *args): QTableWidget.__init__(self, *args) self.resizeColumnsToContents() self.horizontalHeader().setSortIndicatorShown(True) self.horizontalHeader().setStretchLastSection(True) self.horizontalHeader().setCascadingSectionResizes(True) # равномерное изменение ширины столбцов #self.horizontalHeader().setSectionResizeMode(1) # изменение ширины столбцов по размеру текста #self.horizontalHeader().setSectionResizeMode(3) self.horizontalHeader().setStyleSheet("color: blue;") self.setWordWrap(True) self.setSortingEnabled(True) # обработка нажатия мышой на таблице self.doubleClicked.connect(self.on_click) # self.doubleClicked.connect(self.contextMenuEvent(self.cursor())) # показ контекстного меню def contextMenuEvent(self, event): Rmenu = QMenu(self) addRecord = Rmenu.addAction("Добавить запись") delRecord = Rmenu.addAction("Удалить запись") relations = Rmenu.addAction("Показать связанные документы") action = Rmenu.exec_(self.mapToGlobal(event.pos())) if action == delRecord: row = self.rowAt(event.pos().y()) col = self.columnAt(event.pos().x()) print("Удаляем row:%d, col:%d" % (row, col)) item = self.item(self.currentIndex().row(), self.currentIndex().column()) print("Запись" + item.text()) elif action == addRecord: 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()) # Форма для добавления и редактирования class EditForm(QWidget): 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() 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) 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() return app.exec_() # # if __name__ == '__main__': main()