这是我的“main.py”代码:
ser = serial.Serial('COM4', 9600)
flag = 0
GLOBAL_STATE = False
GLOBAL_TITLE_BAR = True
from dashboard import Ui_MainWindow
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# self.ui = Ui_MainWindow()
# self.ui.setupUi(self)
self.ui = uic.loadUi("untitled.ui", self)
self.progressBarValue(0)
self.progress()
self.distance_percent = 0
self.traces = dict()
self.timestamp = 0
self.timeaxis = []
self.distanceaxis = []
self.current_timer_graph = None
# self.csv_file = open(datafile, 'w')
# self.csv_writer = csv.writer(self.csv_file, delimiter=',')
self.graph_lim = 15
self.deque_timestamp = deque([], maxlen=self.graph_lim+20)
self.deque_distance = deque([], maxlen=self.graph_lim+20)
## REMOVE TITLE BAR
self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.graphwidget1 = PlotWidget(title="Distance percent")
x1_axis = self.graphwidget1.getAxis('bottom')
x1_axis.setLabel(text='Time since start (s)')
y1_axis = self.graphwidget1.getAxis('left')
y1_axis.setLabel(text='Percent')
self.show_distance_graph()
self.ui.gridLayout.addWidget(self.graphwidget1, 0, 0, 1, 3)
self.timer = QtCore.QTimer()
self.timer.start(0)
self.ui.pushButton.clicked.connect(lambda: self.slideanimation(400, True))
self.timer.timeout.connect(self.progress)
self.ui.max_button.clicked.connect(lambda: self.maximize_restore())
self.ui.close_button.clicked.connect(lambda: self.close_window())
self.ui.min_button.clicked.connect(lambda: self.min_window())
self.show()
def show_distance_graph(self):
self.graphwidget1.show()
self.start_distance_graph()
def start_distance_graph(self, value):
if self.current_timer_graph:
self.current_timer_graph.stop()
self.current_timer_graph.deleteLater()
self.current_timer_graph = None
self.current_timer_graph = QtCore.QTimer()
self.current_timer_graph.timeout.connect(self.update_distance)
self.current_timer_graph.start(0)
def update_distance(self, value):
self.deque_timestamp.append(self.timestamp)
self.deque_distance.append(value)
self.deque_ram.append(self.ram_percent)
timeaxis_list = list(self.deque_timestamp)
cpu_list = list(self.deque_distance)
if self.timestamp > self.graph_lim:
self.graphwidget1.setRange(xRange=[self.timestamp-self.graph_lim+1, self.timestamp], yRange=[
min(cpu_list[-self.graph_lim:]), max(cpu_list[-self.graph_lim:])])
self.set_plotdata(name="distance", data_x=timeaxis_list,
data_y=cpu_list)
def set_plotdata(self, name, data_x, data_y):
# print('set_data')
if name in self.traces:
self.traces[name].setData(data_x, data_y)
else:
if name == "distance":
self.traces[name] = self.graphwidget1.getPlotItem().plot(
pen=pg.mkPen((85, 170, 255), width=3))
def min_window(self):
self.showMinimized()
def close_window(self):
self.close()
sys.exit()
def maximize_restore(self):
global GLOBAL_STATE
status = GLOBAL_STATE
if status == False:
self.showMaximized()
GLOBAL_STATE = True
self.ui.Background.setContentsMargins(0, 0, 0, 0)
self.ui.max_button.setToolTip("Restore")
##self.ui.maximizeRestoreAppBtn.setIcon(QIcon(u":/icons/images/icons/icon_restore.png"))
##self.ui.frame_size_grip.hide()
##self.left_grip.hide()
##self.right_grip.hide()
##self.top_grip.hide()
##self.bottom_grip.hide()
else:
GLOBAL_STATE = False
self.showNormal()
self.resize(self.width()+1, self.height()+1)
self.ui.Background.setContentsMargins(10, 10, 10, 10)
self.ui.max_button.setToolTip("Maximize")
##self.ui.maximizeRestoreAppBtn.setIcon(QIcon(u":/icons/images/icons/icon_maximize.png"))
##self.ui.frame_size_grip.show()
##self.left_grip.show()
##self.right_grip.show()
##self.top_grip.show()
##self.bottom_grip.show()
def slideanimation(self, maxWidth, enable):
if enable:
print("click")
slider_style = """
QSlider::groove {
border: 1px solid rgba(38, 38, 38,{Grove_Border_trans});
width: 5px;
background: rgba(56, 2, 88,{Grove_Back_trans});
margin: 0 16px;
}
QSlider::handle {
background: rgba(255, 148, 0,{handle_Back_trans});
border: 2px solid rgba(114, 4, 231,{handle_Border_trans});
height: 20px;
margin: -5px -5px;
border-radius: 7px;
}
"""
width = self.ui.Widgetholder.width()
Grove_Border = Grove_Back = handle_Back = handle_Border = str(255)
standard = 351
if width == 351:
newwidth = maxWidth
else:
newwidth = standard
##print(width)
##print("C")
##print(newwidth)
self.animation = QPropertyAnimation(self.ui.Widgetholder, b"minimumWidth")
self.animation.setDuration(400)
self.animation.setStartValue(width)
self.animation.setEndValue(newwidth)
self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
self.animation.start()
newSlidersheet = slider_style.replace("{Grove_Border_trans}", Grove_Border).replace("{Grove_Back_trans}", Grove_Back).replace("{handle_Back_trans}", handle_Back).replace("{handle_Border_trans}", handle_Border)
self.ui.verticalSlider.setStyleSheet(newSlidersheet)
def oxygencircle(self):
oxygenstylesheet = """
QFrame
{
border-radius: 115px;
background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:{oxy_1} rgba(0, 255, 251, 0), stop:{oxy_2} rgba(255, 148, 0, 255));
}
"""
slider_value = self.ui.verticalSlider.value()
intslider_value = int(slider_value)
level = (100-intslider_value)/100.0
Oxy_1 = str(level-0.001)
Oxy_2 = str(level)
print(Oxy_1)
print("C")
print(Oxy_2)
if level == 100:
Oxy_1 = "1.000"
Oxy_2 = "1.000"
newoxystyle = oxygenstylesheet.replace("{oxy_1}", Oxy_1).replace("{oxy_2}", Oxy_2)
self.ui.frame.setStyleSheet(newoxystyle)
def progress(self):
if self.ui.pushButton.clicked.connect(lambda: self.slideanimation(400, True)):
self.oxygencircle()
#print("A")
b = ser.readline()# read a byte string
string_n = b.decode() # decode byte string into Unicode
string = string_n.rstrip() # remove \n and \r
value = float(string)
if value >= 100:
value=100
update_distance(value)
if value>12:
# HTML Text and colour above threshold value
text_stylesheet ="""
background-color:none;
color:{change}
"""
htmltext = """{VALUE}"""
new_color = "#c10003"
#Replace number
newstyle=text_stylesheet.replace("{change}", new_color)
newHtml = htmltext.replace("{VALUE}", str(int(value)))
self.ui.label.setText(newHtml)
self.ui.label.setStyleSheet(newstyle)
self.progressBarValue(value)
else:
# HTML Text and colour under threshold
text_stylesheet ="""
background-color:none;
color:{change}
"""
htmltext = """{VALUE}"""
new_color = "#ffffff"
#Replace number
newstyle=text_stylesheet.replace("{change}", new_color)
newHtml = htmltext.replace("{VALUE}", str(int(value)))
self.ui.label.setText(newHtml)
self.ui.label.setStyleSheet(newstyle)
self.progressBarValue(value)
def progressBarValue(self, value):
styleSheet = """
QFrame{
border-radius: 110px;
background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:{STOP_1} rgba(255, 0, 127, 0), stop:{STOP_2} rgba({color_1}, {color_2}, {color_3}, 255));
}
"""
if value>12:
colour1=str(204)
colour2=str(0)
colour3=str(0)
##print("value ", value)
progress = (100-value)/100.0
stop_1 = str(progress - 0.001)
stop_2 = str(progress)
##print(stop_1)
##print(stop_2)
newStylesheet = styleSheet.replace("{STOP_1}", stop_1).replace("{STOP_2}", stop_2).replace("{color_1}", colour1).replace("{color_2}", colour2).replace("{color_3}", colour3)
self.ui.CircularProgressBar.setStyleSheet(newStylesheet)
##print("G")
else:
colour1=str(85)
colour2=str(85)
colour3=str(255)
##print("value ", value)
progress = (100-value)/100.0
stop_1 = str(progress - 0.001)
stop_2 = str(progress)
##print(stop_1)
##print(stop_2)
newStylesheet = styleSheet.replace("{STOP_1}", stop_1).replace("{STOP_2}", stop_2).replace("{color_1}", colour1).replace("{color_2}", colour2).replace("{color_3}", colour3)
self.ui.CircularProgressBar.setStyleSheet(newStylesheet)
## print("G")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
这是出现的错误:
Traceback (most recent call last):
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\Lib\site-packages\QtDesigner\Projects\Hover + Graph\main.py", line 347, in <module>
window = MainWindow()
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\Lib\site-packages\QtDesigner\Projects\Hover + Graph\main.py", line 44, in __init__
self.ui = uic.loadUi("untitled.ui", self)
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\lib\site-packages\PyQt5\uic\__init__.py", line 238, in loadUi
return DynamicUILoader(package).loadUi(uifile, baseinstance, resource_suffix)
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\lib\site-packages\PyQt5\uic\Loader\loader.py", line 66, in loadUi
return self.parse(filename, resource_suffix)
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\lib\site-packages\PyQt5\uic\uiparser.py", line 1037, in parse
actor(elem)
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\lib\site-packages\PyQt5\uic\uiparser.py", line 822, in createUserInterface
self.toplevelWidget = self.createToplevelWidget(cname, wname)
File "C:\Users\PAVILION\AppData\Local\Programs\Python\Python37\lib\site-packages\PyQt5\uic\Loader\loader.py", line 59, in createToplevelWidget
(type(self.toplevelInst), classname)))
TypeError: ('Wrong base class of toplevel widget', (<class '__main__.MainWindow'>, 'QMainWindow'))
我已将 QMainWindow 作为基类,但出现错误,如何解决此问题。
我遇到了同样的问题,但我已经使用 Claude AI 将 *.ui 文件完全转换为 py 文件,因此我不必担心加载 ui 文件。尝试使用相同的方法,你会很高兴去。