一个任务:
- 在小部件 Frame(PyQt5) 上的 GUI(PyQT5) 中绘制图形(这很重要)。
- 实时图表每秒更新 1 次。X轴是时间轴。
发生了什么:
- 在小部件上绘制图表(仅轴和网格)
什么不起作用:
- 新点未添加到图表中
- 时间轴,尽管进行了设置,但不显示时间。
代码:
from random import uniform
import sys
from PyQt5 import uic, QtChart, QtCore
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtChart import QChart, QChartView, QLineSeries
class Window(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('QtChart.ui', self)
# Create chart
chart = self.create_linechart()
# Create PyQt widget for painting
chart_widget = self.chart
my_layout = QVBoxLayout(chart_widget)
self.chart.setLayout(my_layout)
my_layout.addWidget(chart)
# Setting the axis to display dates
self.axis_x = QtChart.QDateTimeAxis()
self.axis_x.setTickCount(100)
self.axis_x.setFormat("h:mm")
self.axis_x.setTitleText("Date")
# Timer for update data 1 time per second
self.timer_update_events = QTimer()
self.timer_update_events.timeout.connect(self.update_data)
self.timer_update_events.start(1000)
self.show()
def update_data(self):
time_now = QtCore.QDateTime.currentDateTime()
y = uniform(0, 1)
self.series.append(time_now.toMSecsSinceEpoch(), y)
def create_linechart(self):
self.series = QLineSeries()
chart = QChart()
chart.addSeries(self.series)
chart.createDefaultAxes()
chartview = QChartView(chart)
return chartview
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(App.exec_())
如何在 X 轴上添加新点并设置时间?
加载的QtChart.ui接口文件(其代码...创建*.txt文件并重命名QtChart.ui):
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1007</width>
<height>789</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QFrame" name="chart">
<property name="geometry">
<rect>
<x>50</x>
<y>30</y>
<width>901</width>
<height>681</height>
</rect>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(255, 255, 255);</string>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1007</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>