PYQT5 Physics Calculator - python

I am making a physics calculator that takes values from the person and uses a calculation to show the answer. the problem is that when i press submit to take the values and save them as variable and show a button to show the answer, the app closes and sublime text shows REPL closed. i have no idea why. please help
import sys
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QToolTip , QCheckBox, QLCDNumber,QLineEdit,QInputDialog#just compile the modules like this
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QLabel
def ObjectDensity():
dflabel = QLabel("Please Enter Density of Fluid: ",w)
dflabel.move(25,220)
dflabel.show()
dfte = QLineEdit(w)
dfte.move(25,260)
dfte.show()
Weight2 = QLabel("Please Enter Weight:",w)
Weight2.move(25,300)
Weight2.show()
Wte = QLineEdit(w)
Wte.move(25,340)
Wte.show()
AIW2 = QLabel("Enter Apperent Immersed Weight: ",w)
AIW2.move(25,380)
AIW2.show()
aiwte = QLineEdit(w)
aiwte.move(25,420)
aiwte.show()
ansbutton = QPushButton("Submit",w)
ansbutton.move(50,480)
ansbutton.show()
ansbutton.clicked.connect(lambda: f1(dfte,Wte,aiwte,ansdo))
# df1 = dfte.text()
# w2 = Wte.text()
# aiw6 = aiwte.text()
def f1(dfte,Wte,aiwte,ansdo):
df1 = int(dfte.text())
w2 = int(Wte.text())
aiw6 = int(aiwte.text())
# ansdo = ((w2/w2-aiw6)*df1)
# ans4 = int(ansdo)
ans = QPushButton("press to show answer",w)
ans.move(50,250)
ans.show()
ans.clicked.connect(lambda:f2(w2,aiw6,df1))
def f2(w2,aiw6,df1):
ansdo = ((w2/w2-aiw6)*df1)
ans4 = int(ansdo)
answer = QLabel(ans4,w)
answer.move(75,300)
answer.show()
def arch():
l_archimedes = QLabel("Archimedes' Law",w)
l_archimedes.move(25,80)
l_archimedes.show()
l_archimedes2 = QLabel("Density of Object/Density of Fluid = Weight/(Weight - Apparent Immersed Weight)",w)
l_archimedes2.move(25,110)
l_archimedes2.show()
Archimedeslaw = QLabel("What Do You Want to Solve For:",w)
Archimedeslaw.move(25,145)
Archimedeslaw.show()
dop = QPushButton("Density of Object",w)
dop.move(25,160)
dop.show()
dop.clicked.connect(ObjectDensity)
DF = QPushButton("Density of Fluid",w)
DF.move(200,160)
DF.show()
Weight = QPushButton("Weight",w)
Weight.move(375,160)
Weight.show()
AIW = QPushButton("Apperent Immersed Weight",w)
AIW.move(500,160)
AIW.show()
app = QApplication(sys.argv)
w = QWidget()
w.resize(900,600)
w.move(460,0)
w.setWindowTitle("Physics Laws")
L1 = QLabel("Welcome To Physics Laws",w,)
L1.move(25,0)
b1 = QPushButton("Archimedes Law",w)
b1.move(25,45)
b1.clicked.connect(arch)
w. show()
sys.exit(app.exec_())

Try it:
import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel,
QToolTip, QCheckBox, QLCDNumber,
QLineEdit, QInputDialog) # ??? just compile the modules like this
from PyQt5.QtGui import QIcon
def ObjectDensity():
dflabel = QLabel("Please Enter Density of Fluid: ",w)
dflabel.move(25,220)
dflabel.show()
dfte = QLineEdit(w)
dfte.move(25,260)
dfte.show()
Weight2 = QLabel("Please Enter Weight:",w)
Weight2.move(25,300)
Weight2.show()
Wte = QLineEdit(w)
Wte.move(25,340)
Wte.show()
AIW2 = QLabel("Enter Apperent Immersed Weight: ",w)
AIW2.move(25,380)
AIW2.show()
aiwte = QLineEdit(w)
aiwte.move(25,420)
aiwte.show()
ansbutton = QPushButton("Submit",w)
ansbutton.move(50,480)
ansbutton.show()
ansbutton.clicked.connect(lambda: f1(dfte,Wte,aiwte )) #,ansdo)) # <------------------
# df1 = dfte.text()
# w2 = Wte.text()
# aiw6 = aiwte.text()
def f1(dfte,Wte,aiwte): #,ansdo): # <------------------
df1 = int(dfte.text())
w2 = int(Wte.text())
aiw6 = int(aiwte.text())
# ansdo = ((w2/w2-aiw6)*df1)
# ans4 = int(ansdo)
ans = QPushButton("press to show answer", w)
#ans.move(50,250)
ans.move(50, 520) # <------------------
ans.show()
answer.hide() # <------------------
ans.clicked.connect(lambda: f2(w2, aiw6, df1))
def f2(w2, aiw6, df1):
print("def f2(w2=`{}`, \naiw6=`{}`, \ndf1=`{}`):".format(w2, aiw6, df1) )
ansdo = ((w2/w2-aiw6)*df1) # w2/w2 = 1 <--- ???
#ans4 = int(ansdo)
#answer = QLabel(ans4, w)
#answer.move(75,300)
answer.setText(str(ansdo)) # <------------------
answer.show() # <------------------
def arch():
l_archimedes = QLabel("Archimedes' Law",w)
l_archimedes.move(25,80)
l_archimedes.show()
l_archimedes2 = QLabel("Density of Object/Density of Fluid = Weight/(Weight - Apparent Immersed Weight)",w)
l_archimedes2.move(25,110)
l_archimedes2.show()
Archimedeslaw = QLabel("What Do You Want to Solve For:",w)
Archimedeslaw.move(25,145)
Archimedeslaw.show()
dop = QPushButton("Density of Object",w)
dop.move(25,160)
dop.show()
dop.clicked.connect(ObjectDensity)
DF = QPushButton("Density of Fluid",w)
DF.move(200,160)
DF.show()
Weight = QPushButton("Weight",w)
Weight.move(375,160)
Weight.show()
AIW = QPushButton("Apperent Immersed Weight",w)
AIW.move(500,160)
AIW.show()
app = QApplication(sys.argv)
w = QWidget()
w.resize(900,600)
w.move(460,0)
w.setWindowTitle("Physics Laws")
L1 = QLabel("Welcome To Physics Laws",w,)
L1.move(25,0)
b1 = QPushButton("Archimedes Law",w)
b1.move(25,45)
b1.clicked.connect(arch)
answer = QLabel(w) # <------------------
answer.move(50, 550) # <------------------
w. show()
sys.exit(app.exec_())

Related

ufunc 'fmin' did not contain a loop with signature matching types When trying to make graph

I can't make graph with qt6 beacouse when I set values it gives me error: numpy.core._exceptions._UFuncNoLoopError: ufunc 'fmin' did not contain a loop with signature matching types (dtype('<U1'), dtype('<U1')) -> None
Theres my code:
import sys
from PySide6.QtWidgets import QApplication
from PySide6 import *
import pyqtgraph as pg
uiclass, baseclass = pg.Qt.loadUiType("mainwindow.ui")
class MainWindow(uiclass, baseclass):
def __init__(self):
super().__init__()
self.setupUi(self)
self.plot([1,2,3,4,5,6,7,8,9,10], [20,20,20,20,20,20,20,20,20,20])
self.pushButton.clicked.connect(lambda: self.changeColorTeeth1())
self.pushButton_2.clicked.connect(lambda: self.changeColorTeeth2())
self.pushButton_3.clicked.connect(lambda: self.changeColorTeeth3())
self.pushButton_4.clicked.connect(lambda: self.changeColorTeeth4())
self.pushButton_5.clicked.connect(lambda: self.changeColorTeeth5())
self.pushButton_6.clicked.connect(lambda: self.changeColorTeeth6())
self.SaveGraphButton.clicked.connect(lambda: self.Save())
def plot(self, teethsize, height):
self.graphWidget.plot(teethsize, height)
self.graphWidget_2.plot(teethsize, height)
def Save(self):
print("Save runned!")
Teeth1 = self.Teeth1.toPlainText()
Teeth2 = self.Teeth2.toPlainText()
Teeth3 = self.Teeth3.toPlainText()
Teeth4 = self.Teeth4.toPlainText()
Teeth5 = self.Teeth5.toPlainText()
Teeth6 = self.Teeth6.toPlainText()
Teeth7 = self.Teeth7.toPlainText()
Teeth8 = self.Teeth8.toPlainText()
Teeth9 = self.Teeth9.toPlainText()
Teeth10 = self.Teeth10.toPlainText()
Teeth11 = self.Teeth11.toPlainText()
Teeth12 = self.Teeth12.toPlainText()
Teeth13 = self.Teeth13.toPlainText()
Teeth14 = self.Teeth14.toPlainText()
self.plot([Teeth1,Teeth2,Teeth3,Teeth4,Teeth5,Teeth6,Teeth7,Teeth8,Teeth9,Teeth10,Teeth11,Teeth12,Teeth13,Teeth14], [20,20,20,20,20,20,20,20,20,20,20,20,20,20])
def changeColorTeeth1(self):
g = open('config.txt', 'r')
buttonClicked = int(g.read())
print("Button State:", buttonClicked)
g.close()
f = open('config.txt', 'w')
if buttonClicked == 0:
self.pushButton.setStyleSheet(f"background-color : orange;")
buttonClicked = 1
elif buttonClicked == 1:
self.pushButton.setStyleSheet(f"background-color : red;")
buttonClicked = 2
elif buttonClicked == 2:
self.pushButton.setStyleSheet(f"background-color : white;")
buttonClicked = 0
b = f.write(str(buttonClicked))
f.close()
...
I tried to add str and int but it still doesn't worked!

How to set my QTreeWidget expanded by default?

I have this QTreeWidget that I would like to be expanded by default.
I have read this same question many times but the solutions aren't working for me. I tried the commands for the root of my tree:
.ExpandAll() and .itemsExpandable()
and for the children .setExpanded(True) with no success.
Here is the code of my test application:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget,
QTreeWidget, QTreeWidgetItem, QVBoxLayout
)
# ----------------------------------------------------------------
unsorted_data = [
['att_0', 'a', 2020],
['att_0', 'a', 2015],
['att_2', 'b', 5300],
['att_0', 'a', 2100],
['att_1', 'b', 5013],
['att_1', 'c', 6500],
]
# Sort data
list_att = []
for elem in range(len(unsorted_data)) :
att_ = unsorted_data[elem][0]
if att_ not in list_att:
list_att.append(att_)
list_att.sort()
n_att = len(list_att)
data = ['']*n_att
tree = ['']*n_att
list_a_number = []
list_b_number = []
list_c_number = []
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
widget = QWidget()
layout = QVBoxLayout()
widget.setLayout(layout)
# QTreeWidget
main_tree = QTreeWidget()
main_tree.setHeaderLabel('Test')
# main_tree.itemsExpandable() # NOT WORKING
# main_tree.expandAll() # NOT WORKING
sublevel_1 = []
for i, att in enumerate(list_att) :
list_a_number.clear()
list_b_number.clear()
list_c_number.clear()
# Create a dictionary
for elem in range(len(unsorted_data)) :
if unsorted_data[elem][0] == att :
if unsorted_data[elem][1]== 'a' :
list_a_number.append(str(unsorted_data[elem][2]))
if unsorted_data[elem][1] == 'b' :
list_b_number.append(str(unsorted_data[elem][2]))
if unsorted_data[elem][1] == 'c' :
list_c_number.append(str(unsorted_data[elem][2]))
data[i] = {'a' : list_a_number, 'b' : list_b_number, 'c' : list_c_number}
# Fill the Tree
items = []
att_id = list_att[i].split('\\')[-1]
tree[i] = QTreeWidgetItem([att_id])
tree[i].setExpanded(True) # NOT WORKING
sublevel_1.append(tree[i])
for key, values in data[i].items():
item = QTreeWidgetItem([key])
item.setCheckState(0, Qt.Checked)
tree[i].addChild(item)
for value in values :
child = QTreeWidgetItem([value])
child.setExpanded(True) # NOT WORKING
child.setCheckState(0, Qt.Checked)
item.addChild(child)
items.append(item)
main_tree.insertTopLevelItems(0, sublevel_1)
layout.addWidget(main_tree)
self.setCentralWidget(widget)
# ------------------------------------------------------------------
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Try expandAll:
child.expandAll()
You have to use expandAll after placing all the items in the QTreeWidget:
main_tree.insertTopLevelItems(0, sublevel_1)
main_tree.expandAll()
layout.addWidget(main_tree)
Note: One of the errors in your case is that you invoke setExpanded before the item is added to the QTreeWidget. remove useless setExpanded

Seperating concerns in PyQt5 GUI app. Need seperate Qthread for concurrency

I have a simple GUI window made using PyQt5 Library.
`
import sys, csv, time
from datetime import datetime
from time import strftime,localtime
import threading
import pandas as pd
import numpy as np
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel, QTextEdit, QInputDialog, QLineEdit
from PyQt5 import QtCore
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5 import uic
from trade import trade
from pyqtgraph import PlotWidget
import pyqtgraph as pg
from itertools import islice
class UpdateThread(QThread):
signal = pyqtSignal()
def __init__(self, gui):
QThread.__init__(self)
self.gui = gui
def run(self):
try:
# timer = pg.QtCore.QTimer()
# timer.timeout.connect(UI.update_plot(self))
# timer.start(50)
while(True):
self.signal.emit()
time.sleep(5)
except Exception as e:
print(e)
class UI(QMainWindow):
gui = None
p_l = 0.0
display_trades = ''
def __init__(self):
super(UI, self).__init__()
global gui
gui = uic.loadUi('rightside.ui', self)
self.initUI()
self.timer_thread = UpdateThread(gui)
self.timer_thread.signal.connect(self.update_plot)
self.timer_thread.start()
def initUI(self):
self.prices = self.read_prices()
trades = self.get_trades()
list_trade_prices = trades[0].values.tolist()
list_trade_sizes = trades[1].values.tolist()
list_trade_ids = trades[4].drop_duplicates().values.tolist()
as_floats = np.array(list_trade_prices).astype(np.float)
self.set_fields(self.prices)
gui.update_button.clicked.connect(self.on_click)
gui.cancel_button.clicked.connect(self.on_exit)
self.show()
def get_trades(self):
df = pd.DataFrame()
# Get 50 most recent trades
trades = islice(trade.get_product_trades(), 192)
for x in reversed(list(trades)):
# if x['trade_id'] > last_id:
if x['side'] == 'buy':
#more trades that hit the bid force price down
new_row = {0:x['price'], 1:x['size'], 2:1, 3:time.mktime(datetime.timetuple(datetime.now())), 4:x['trade_id']}
df = df.append(new_row, ignore_index=True)
bid_side = True
else:
#more trades that hit the offer force force price up
new_row = {0:x['price'], 1:x['size'], 2:0, 3:time.mktime(datetime.timetuple(datetime.now())), 4:x['trade_id']}
df = df.append(new_row, ignore_index=True)
df = df.drop_duplicates([4], keep='last')
return df
def update_plot(self):
global gui
#set results_chart
trades = UI.get_trades(self)
list_trade_prices = trades[0].values.tolist()
last_price = list_trade_prices[-1]
as_floats = np.array(list_trade_prices).astype(np.float)
gui.results.setText("{0:,.2f}".format(float(last_price)))
gui.results_chart.clear()
gui.results_chart.plot(as_floats)
gui.statusBar().showMessage('Connected')
self.monitor_prices(last_price)
prices = self.read_prices()
self.set_fields(prices)
def get_open_trades(self, btc):
sum_buys = 0.0
open_trades = []
if float(btc) != 0:
for i in trade.get_last_fills():
if i['side'] == 'buy':
sum_buys += float(i['size'])
open_trades.append([i['price'], i['size']])
if sum_buys >= float(btc):
break
return open_trades
def monitor_prices(self, last_price):
global gui
date_local = strftime("%A, %d %b %Y %H:%M:%S", localtime())
stop_enter_price = float(gui.enter_box.toPlainText())
usd = gui.usd_display.text().replace(',', '')
btc = gui.btc_display.text()
trade_amount = ''
if float(last_price) > stop_enter_price and stop_enter_price != 0.0:
if float(usd) > 10.00:
trade_amount = "{0:.2f}".format((float(usd)+(float(btc)*float(last_price)))*0.02718)
result = trade.buy_market(trade_amount)
gui.statusBar().showMessage(str(result))
gui.enter_box.setText('')
with open('stop_enter.txt', 'w') as enter:
enter.write('0.0')
with open('../trades/buys.csv','a') as buys:
writer = csv.writer(buys)
writer.writerow([date_local, last_price, trade_amount, result])
open_trades = self.get_open_trades(btc)
display_trades = ''
trade_amount = 0.0
total_amount = 0.0
STOP_RATE = 0.02
if len(open_trades) != 0:
highest_entry_price = float(open_trades[0][0])
lowest_entry_price = float(open_trades[0][0])
#find lowest price and set stop-loss 2% below that and increment it up
for i,j in enumerate(open_trades):
difference = (float(last_price) - float(open_trades[i][0]))*float(open_trades[i][1])
total_amount += difference
per_diff = str((float(last_price) - float(open_trades[i][0])) / float(open_trades[i][0]))
display_trades += f'{"{0:.3f}".format(float(per_diff)*100)}%\t'
gui.statusBar().showMessage(display_trades)
if highest_entry_price < float(open_trades[i][0]):
highest_entry_price = float(open_trades[i][0])
if lowest_entry_price > float(open_trades[i][0]):
lowest_entry_price = float(open_trades[i][0])
#1R
if float(per_diff) < -STOP_RATE:
if float(btc) > 0.001:
trade_amount = "{0:.8f}".format(float(j[1]))
response = trade.sell_market(trade_amount)
with open('stop_loss.txt', 'w') as enter:
enter.write('0.0')
gui.statusBar().showMessage(str(response))
if float(last_price) < float(gui.stop_box.toPlainText()):
if float(btc) > 0.001:
trade_amount = "{0:.8f}".format(float(btc))
response = trade.sell_market(trade_amount)
gui.statusBar().showMessage(str(response))
def on_click(self):
global gui
enter_price = gui.enter_box.toPlainText()
stop_price = gui.stop_box.toPlainText()
self.write_prices('stop_enter.txt', enter_price)
self.write_prices('stop_loss.txt', stop_price)
gui.statusBar().showMessage('Updated Successfully!')
time.sleep(1.618)
gui.statusBar().showMessage('')
def on_exit(self):
sys.exit(0)
def write_disk(self, date_local, current_price, trade_amount, note, response):
with open('../trades/sells.csv','a') as sells:
writer = csv.writer(sells)
writer.writerow([date_local, current_price, trade_amount, note, response])
def take_it(self, risk_reward, btc):
if float(btc) > 0.001:
response = trade.sell_market(btc)
# playsound(path+'/sounds/sellit.mp3')
write_disk(date_local, current_price, trade_amount, risk_reward, response)
def write_prices(self, file_name, price):
with open(file_name, 'w') as file:
file.write(price)
def set_fields(self, prices):
global gui, p_l
last_price_data = trade.get_last_price()
last_price = last_price_data['price']
last_fill_data = None
while(True):
last_fill_data = trade.get_last_fill()
if 'trade_id' in last_fill_data:
break
last_fill = '0.0'
if last_fill_data['side'] != 'sell':
last_fill = last_fill_data['price']
p_l = float(last_price) - float(last_fill)
gui.enter_box.setText(prices[0])
gui.stop_box.setText(prices[1])
gui.results.setText("{0:,.2f}".format(p_l))
gui.in_price.setText("{0:,.2f}".format(float(last_fill)))
gui.usd_display.setText("{0:,.2f}".format(float(trade.get_usd())))
gui.btc_display.setText("{0:,.8f}".format(float(trade.get_btc())))
def read_prices(self):
content = []
with open('stop_enter.txt', 'r') as enter:
stop_enter = enter.readlines()
content.append(stop_enter[0].rstrip())
with open('stop_loss.txt', 'r') as stop:
stop_loss = stop.readlines()
content.append(stop_loss[0].rstrip())
return content
app = QApplication(sys.argv)
ex = UI()
app.exec_()
`
I am not too familiar with qthreads and how to get them to work. And advice would be greatly appreciated. I just want to Updatethread to call the update_plot once every like 2 seconds or so. Thought this would be pretty simple but this is giving me a headache at this point.
I tried putting the Qtimer in the other thread but then I get an error like 'cannot start timer from other thread'
Thanks for all you help my programmer friends.
For some timing updates it's better to use QTimer and its signal timeout:
from PyQt5.QtCore import QTimer
class UI(QMainWindow):
def __init__(self):
super(UI, self).__init__()
self.timer = QTimer(self)
self.timer.timeout.connect(self.self.update_plot)
# Set 2 seconds interval and start the timer
self.timer.start(2000)
def update_slot(self):
#...

Python is crashing while trying to clear combobox in pyqt5

I started today with qt compiler, so I don't have much experience in building gui. My project is about to create dynamic smart check boxes to define axes and at the end to plot several subplots to a figure.
I tried to create dynamic combo boxes that change every time I change my current selection in the combo box.
The big issue is that it crash every time i try to change a selection in the combo box.
I tried to use .clear() method but it crash every time I clicked on it.
Edit: I changed the code to make producible code. After clicking on "Load Files", you will be able the combo boxes filled. If you will change the combo box "Choose message" for example, the python crash.
The GUI
# ------------------------------------------------- -----
# ---------------------- main.py ------------------- ----
# --------------------------------------------- ---------
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.uic import loadUi
from PyQt5.QtCore import pyqtSlot
import threading , os, subprocess, importlib, platform
# Decode_class = 'MAVLinkBinFileDecoder'
# Module = importlib.import_module(Decode_class)
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar )
import numpy as np
import random
class MatplotlibWidget(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("gui.ui", self)
self.setWindowTitle ( "PyQt5 & Matplotlib Example GUI" )
self.loadfiles = 0
self.first_run = 0
self.progressBar.setProperty("value", 0)
# self.pushButton_load_files.setEnabled(False)
self.pushButton_add_to_graph.setEnabled(False)
self.pushButton_choose_xml_file.clicked.connect(self.open_xml_FileNamesDialog)
self.pushButton_choose_bin_files.clicked.connect(self.open_bin_FileNamesDialog)
self.pushButton_load_files.clicked.connect(self.load_files)
self.comboBox_choose_file.currentIndexChanged.connect(self.selectionchange_file)
self.comboBox_message.currentIndexChanged.connect(self.selectionchange_message)
self.comboBox_system_id.currentIndexChanged.connect(self.selectionchange_system_id)
self.pushButton_save_plot.clicked.connect(self.update_graph)
self.file_to_graph_demo = [({'HEARTBEAT':[{'type':[12],'autopilot':[0]},{'type':[2,2,0],'autopilot':[0,0,0]}], 'CHAMBER_STATUS':[{'time_boot_ms':[1,1,1], 'chamber_num':[1,2,3]}], 'ATTITUDE':[{'test':[0,0,0,],'check':[1,1,1]}, {'test':[0,0,0,],'check':[1,1,1]}, 0 , 0, {'test':[0,0,0,],'check':[1,1,1]}]},'test')]
self.addToolBar(NavigationToolbar(self .MplWidget.canvas, self))
#pyqtSlot()
def open_xml_FileNamesDialog(self):
self.loadfiles += 1
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.filename, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
"Xml Files (*.xml)", options=options)
if self.loadfiles == 2:
self.pushButton_load_files.setEnabled(True)
self.pushButton_choose_xml_file.setVisible(False)
#pyqtSlot()
def open_bin_FileNamesDialog(self):
self.loadfiles += 1
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.list_of_file_paths, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
"Bin Files (*.bin)", options=options)
if self.loadfiles == 2:
self.pushButton_load_files.setEnabled(True)
self.pushButton_choose_bin_files.setVisible(False)
#pyqtSlot()
def load_files(self):
# parse = Module.Logic_bin_to_mat_parser(self.filename[0])
# parse.generate_dialect_from_xml() # Run Mavgenerate xml function
# value = 19
# self.progressBar.setProperty("value", value)
# self.file_to_graph = []
# for path in self.list_of_file_paths: # Parse and create Matlab from each bin file
# parse.decode_messages(path)
# parse.create_dictionary_of_amount_of_messages_by_type()
# parse.parse_bin_to_mat()
# self.file_to_graph.append((parse.save, parse.file_base_name))
# parse.convert_parse_dictionary_to_mat()
# value += (100 - 20) / len(self.list_of_file_paths)
# self.progressBar.setProperty("value", value)
# value = 100
# self.progressBar.setProperty("value", value)
# self.pushButton_load_files.setVisible(False)
# self.progressBar.setVisible(False)
for option in self.file_to_graph_demo:
self.comboBox_choose_file.addItem(option[1])
#pyqtSlot()
def selectionchange_file(self):
self.first_run += 1
combobox_enty = self.comboBox_choose_file.currentText()
self.file_idx = self.comboBox_choose_file.findText(combobox_enty)
list_of_messages = []
for message in self.file_to_graph_demo[self.file_idx][0].items():
list_of_messages.append(message[0])
if self.first_run >= 1:
self.comboBox_message.clear()
self.comboBox_message.addItems(list_of_messages)
#pyqtSlot()
def selectionchange_message(self):
self.first_run += 1
self.combobox_entry_message = self.comboBox_message.currentText()
self.message_idx = self.comboBox_message.findText(self.combobox_entry_message)
list_of_system_ids = []
count = 0
for idx, system_id in enumerate(self.file_to_graph_demo[self.file_idx][0][self.combobox_entry_message]):
if system_id != 0:
count += 1
list_of_system_ids.append(str(idx+1))
if self.first_run >= 2:
self.comboBox_system_id.clear()
self.comboBox_system_id.addItems(list_of_system_ids)
#pyqtSlot()
def selectionchange_system_id(self):
self.combobox_entry_system_id = int(self.comboBox_system_id.currentText())-1
self.system_id_idx = self.comboBox_system_id.findText(str(self.combobox_entry_system_id))
for field in self.file_to_graph_demo[self.file_idx][0][self.combobox_entry_message][self.system_id_idx]:
self.comboBox_y_axis.addItem(field)
self.comboBox_x_axis.addItem(field)
def update_graph(self):
fs = 500
f = random.randint(1, 100)
ts = 1 / fs
length_of_signal = 100
t = np . linspace (0, 1, length_of_signal )
cosinus_signal = np . cos ( 2 * np . pi * f * t )
sinus_signal = np . sin ( 2 * np . pi * f * t )
self.MplWidget.canvas.axes.clear()
self.MplWidget.canvas.axes.plot(t,cosinus_signal)
self.MplWidget.canvas.axes.plot(t,sinus_signal)
self.MplWidget.canvas.axes.legend(('cosinus', 'sinus'), loc='upper right')
self.MplWidget.canvas.axes.set_title(' Cosinus - Sinus Signal')
self.MplWidget.canvas.draw()
if __name__ == '__main__':
app=QApplication([])
app.setStyle('Fusion')
window=MatplotlibWidget()
window.show()
app.exec_()
Your issue seems to be in MatplotlibWidget.selectionchange_system_id(). You are trying to cast the current text of self.comboBox_system_id to an int, but this will cause an exception when the current text can't be converted. This is the case just after self.comboBox_system_id is cleared because at that point the current text of the combi box is an empty string. The easiest way to get around this is to test if the current text can be cast to an integer first before continuing, i.e.
def selectionchange_system_id(self):
if self.comboBox_system_id.currentText().isdigit():
self.combobox_entry_system_id = int(self.comboBox_system_id.currentText())-1
...

Add UserControl on WinForm pythonnet

I am trying to add UserControl to a WinForm using PythonNet but not having any luck. For testing, I added a button and that shows up but not the UserControl and I am not sure what I a doing wrong.
All the code can be placed into one py file. I broke into a few sections hoping it will be easier to read.
USER CONTROL
class Field(WinForms.UserControl):
def __init__(self):
self.InitializeComponents()
pass
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.label = WinForms.Label()
self.textBox = WinForms.Label()
## Label
# self.label.Anchor = ((WinForms.AnchorStyles)(
# ((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)))
self.label.AutoSize = True
self.label.Location = System.Drawing.Point(3, 7)
self.label.Name = "label"
self.label.Size = System.Drawing.Size(29, 13)
self.label.TabIndex = 0
self.label.Text = "label"
## TextBox
# self.textBox.Anchor = ((WinForms.AnchorStyles)(
# (((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)
# | WinForms.AnchorStyles.Right)))
# self.textBox.Location = System.Drawing.Point(115, 3)
self.textBox.Name = "textBox"
self.textBox.Size = System.Drawing.Size(260, 20)
self.textBox.TabIndex = 1
## Control
self.AutoScaleMode = WinForms.AutoScaleMode.Font
self.Controls.Add(self.textBox)
self.Controls.Add(self.label)
self.Name = "Field"
self.Size = System.Drawing.Size(378, 26)
# self.PerformLayout()
PARENT FORM
class ParentForm(WinForms.Form):
def __init__(self):
self.InitializeComponents()
# region Form Design
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
self.ClientSize = System.Drawing.Size(385, 180)
self.Name = "ParentForm"
self.Text = "Parent Form"
self.field1 = Field()
self.field1.Location = Point(13, 13)
self.field1.Name = "field1"
self.field1.Size = Size(378, 26)
self.field1.TabIndex = 1
self.Controls.Add(self.field1)
self.button1 = WinForms.Button()
self.button1.Location = Point(13, 50)
self.button1.Size = Size(50, 20)
self.button1.Text = "Button1"
self.Controls.Add(self.button1)
pass
def Dispose(self):
self.components.Dispose()
WinForms.Form.Dispose(self)
ENTRY POINT AND IMPORTS
import clr
import System
import System.Windows.Forms as WinForms
from System.IO import File
from System.Text import Encoding
from System.Drawing import Color, Point, Size
from System.Threading import ApartmentState, Thread, ThreadStart
def appThread():
app = ParentForm()
WinForms.Application.Run(app)
app.Dispose()
def appEntry():
thread = Thread(ThreadStart(appThread))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
if __name__ == '__main__':
appEntry()

Categories

Resources