开始学习PyQt。看了很多关于PyQt和OOP的教程。对于简单的情况,逻辑或多或少是清楚的。但是当涉及到从更简单的元素构建更复杂的代码时,代码在OOP中的结构并不完全清楚。
目标是构建一个窗口,上面有两个Layout
(左和右)。窗口的左半部分应显示一个表格,其中包含从 csv 文件加载的数据。在窗口的右半部分,有一个根据这些表格数据构建的图表。
有两个工人代码分别执行这些任务中的每一个。
告诉我如何将两个代码合二为一,或者至少应该是什么代码结构。
代码открытия/записи csv-файла
:
import sys
import os
import csv
from PyQt5.QtWidgets import QTableWidget, QApplication, QMainWindow, QTableWidgetItem, QFileDialog
from PyQt5.QtWidgets import qApp, QAction
class MyTable(QTableWidget):
def __init__(self, r, c):
super().__init__(r, c)
self.check_change = True
self.init_ui()
def init_ui(self):
self.cellChanged.connect(self.c_current)
self.show()
def c_current(self):
if self.check_change:
row = self.currentRow()
col = self.currentColumn()
value = self.item(row, col)
value = value.text()
print("The current cell is ", row, ", ", col)
print("In this cell we have: ", value)
def open_sheet(self):
self.check_change = False
path = QFileDialog.getOpenFileName(self, 'Open CSV', os.getenv('HOME'), 'CSV(*.csv)')
if path[0] != '':
with open(path[0]) as csv_file:
self.setRowCount(0)
self.setColumnCount(2)
my_file = csv.reader(csv_file, dialect='excel')
for row_data in my_file:
row = self.rowCount()
self.insertRow(row)
if len(row_data) > 2:
self.setColumnCount(len(row_data))
for column, stuff in enumerate(row_data):
item = QTableWidgetItem(stuff)
self.setItem(row, column, item)
self.check_change = True
def save_sheet(self):
path = QFileDialog.getSaveFileName(self, 'Save CSV', os.getenv('HOME'), 'CSV(*.csv)')
if path[0] != '':
with open(path[0], 'w', newline='') as csv_file:
writer = csv.writer(csv_file, dialect='excel')
for row in range(self.rowCount()):
row_data = []
for column in range(self.columnCount()):
item = self.item(row, column)
if item is not None:
row_data.append(item.text())
else:
row_data.append('')
writer.writerow(row_data)
class Sheet(QMainWindow):
def __init__(self):
super().__init__()
self.form_widget = MyTable(10, 2)
self.setCentralWidget(self.form_widget)
col_headers = ['x', 'y']
self.form_widget.setHorizontalHeaderLabels(col_headers)
# Set up menu
bar = self.menuBar()
file = bar.addMenu('Файл')
save_action = QAction('&Сохранить', self)
save_action.setShortcut('Ctrl+S')
open_action = QAction('&Открыть', self)
quit_action = QAction('&Выйти', self)
file.addAction(save_action)
file.addAction(open_action)
file.addAction(quit_action)
quit_action.triggered.connect(self.quit_app)
save_action.triggered.connect(self.form_widget.save_sheet)
open_action.triggered.connect(self.form_widget.open_sheet)
self.setGeometry(700, 300, 300, 500)
self.show()
def quit_app(self):
qApp.quit()
app = QApplication(sys.argv)
sheet = Sheet()
sys.exit(app.exec_())
代码для вывода графика Matplotlib
:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class App(QMainWindow):
def __init__(self):
super().__init__()
self.left = 600
self.top = 300
self.title = 'График'
self.width = 640
self.height = 400
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
m = PlotCanvas(self, width=5, height=4)
m.move(0,0)
button = QPushButton('Кнопка', self)
button.setToolTip('Подсказка')
button.move(500,0)
button.resize(100,20)
self.show()
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0,1,2,3,4,5,6,7,8,9,10]
ax = self.figure.add_subplot(111)
ax.plot(x, y, 'r-')
ax.set_title('График')
self.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
试试这样:
主文件
q1268638_2.py