Results 1 to 7 of 7

Thread: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

  1. #1
    Join Date
    Nov 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Windows

    Default Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    Im using PyQt and/or Qt4 C++ for the first time and trying create simple math calculations. What I need to do is use data from 2 inputs (QLineEdit) and run this calculation in the background:

    a - b = c
    c * 2 = d / 0.9 = sum

    The sum would then need to be printed on another QLineEdit. Is this possible in either PyQT or C++? An answer in either language would be much appreciated as I am using both.

    Also, just so all of my questions are out there, I have a number in QLineEdit and I need to find a data output based on a number range. Example:

    Input Number = 0.80

    0.00 - 0.19 = 5
    0.20 - 0.49 = 10
    0.50 - 0.79 = 15
    0.80 - 1.09 = 20

    So the output (20 in this case) would need to also be output in another QLineEdit.

    Basically, the outputs are in QLineEdit because sometimes we need to change the value based on certain variables (weather, previous fertilizer applications, etc.) I am just a hobby programmer and I mainly work as a soil consultant so I am trying to build a program that inputs my lab data and I can run my calculations and speed up my turn around time. My company already runs calculations based in Excel and VB but I thought that it would be a fun project for me to try and build a new program in Qt. I have been spending countless hours in documentation, books, and tutorials and there are no answers anywhere. If there is any help that you can give me or at least give a link to something that may help, it would be greatly appreciated. Thank you very much and happy coding!

  2. #2
    Join Date
    Jan 2008
    Location
    Alameda, CA, USA
    Posts
    5,230
    Thanks
    302
    Thanked 864 Times in 851 Posts
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    What I need to do is use data from 2 inputs (QLineEdit) and run this calculation in the background:

    a - b = c
    c * 2 = d / 0.9 = sum
    So if I understand you correctly, your user will type a number into each line edit (a and b), and when she is done, your program will run the two numbers through the equations above and display the result in another line edit? Where does "d" come from? Do you mean:

    d = c * 2
    sum = d / 0.9

    ??

    As far as retrieving the numbers from the line edits, that's simple (in C++; I don't know Python well enough to ensure my example would be correct):
    Qt Code:
    1. void MyDataEntryForm::calculateAndDisplaySum()
    2. {
    3. double a = lineEditA->text().toDouble();
    4. double b = lineEditB->text().toDouble();
    5. double sum = ((a - b) * 2.0) / 0.9;
    6. lineEditSum->setText( QString::number( sum, 'g', 2 ) ); // which will give a number like 'nn.nn'; change the 2 to something else for more decimals
    7. }
    To copy to clipboard, switch view to plain text mode 

    You have at least two options for getting the numbers from line edits A and B:

    - An Excel-like mode, where as soon as either number changes, line edit Sum gets updated
    - A "batch" mode, where the user has to click an "update" or "calculate" button before the sum gets updated

    If your users are used to Excel, this might be a more natural mode of use. If you implement the batch mode option, then you do nothing when the values are edited, but you connect the "clicked()" signal from your calculate pushbutton to a slot that executes the code above:

    Qt Code:
    1. MyDataEntryForm::MyDataEntryForm() : ui( new Ui::MyDataEntryForm )
    2. {
    3. ui->setupUi( this );
    4. connect( ui->calculateBtn, SIGNAL( clicked() ), this, SLOT( onCalculateClicked() ) );
    5. }
    6.  
    7. void MyDataEntryForm::onCalculateClicked()
    8. {
    9. calculateAndDisplaySum();
    10. }
    To copy to clipboard, switch view to plain text mode 

    If you use the Excel mode, then it is a bit more complicated, since you need to monitor the A and B line edits for changes and do the calculation dynamically:

    Qt Code:
    1. MyDataEntryForm::MyDataEntryForm() : ui( new Ui::MyDataEntryForm )
    2. {
    3. ui->setupUi( this );
    4. connect( ui->lineEditA, SIGNAL( editingFinished() ), this, SLOT( onEditingFinished ) );
    5. connect( ui->lineEditB, SIGNAL( editingFinished() ), this, SLOT( onEditingFinished ) );
    6. }
    7.  
    8. void MyDataEntryForm::onEditingFinished()
    9. {
    10. // We don't care which line edit changed, since we do the same thing for each of them
    11. calculateAndDisplaySum();
    12. }
    To copy to clipboard, switch view to plain text mode 

    Now, none of this code has any error checking. What if the user enters "tater tots" instead of "42.0" in one of the line edits? So you could get fancier. If there are prescribed allowed ranges for A or B, you could install QDoubleValidator instances on each line edit to ensure that the user can't enter anything other than a valid number. If you install a validator, the editingFinished() signal will not be emitted unless a valid value is entered, so you can be assured that by the time it gets to your calculation, everything is valid.

    This will work with either interaction style - but you will need to manually check the validator state using the input text if you use the pushbutton style of interaction. I don't remember if the validator will allow an invalid entry to be made in the line edit; what I do remember is that the editingFinished() signal isn't emitted unless the input is valid, so this is a safer way to ensure correct inputs.

    As for your last question about converting a number in a range to a fixed value, if you have a predetermined set of ranges and outputs, the simplest way is just an if/else construct:

    Qt Code:
    1. double output = 0.0;
    2.  
    3. if ( 0.00 <= input && input < 0.20 ) // what if the input is between 0.19 and 0.20? Your equations don't cover those corner cases. This does.
    4. output = 5.0;
    5. else if ( 0.20 <= input && input < 0.50 )
    6. output = 10.0;
    7. else if ( 0.50 <= input && input < 0.80 )
    8. output = 15.0;
    9. else if ( 0.80 <= input && input < 1.10 )
    10. output = 20.0;
    11. else
    12. {
    13. // error, so take appropriate action
    14. }
    To copy to clipboard, switch view to plain text mode 

    Good luck.
    Last edited by d_stranz; 28th November 2015 at 19:50.

  3. #3
    Join Date
    Nov 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    Thank you so so much for this. I haven't had a chance to put it to the test yet, but this definitely is getting my mind a step in the right direction!

    I apologize for not making the first equation clear, upon second glance I see how it is confusing. Here is what I am trying to say:

    a - b = c

    c * 2 = sum (d)

    d / 0.9 = sum

    Basically I am subtracting two numbers to get that sum, then taking that and multiplying by 2, and then finally taking the sum of that and dividing that by 0.9 to get to the final answer.

    I am using QtCreator 5.5. I have 4 default source files that are associated with a new project (mainwindow.h, main.cpp, mainwindow.cpp, and mainwindow.ui). Where would this Qt code going that you are giving? In the mainwindow.cpp?

    I prefer the batch method of generating answers. I have a button in the UI that I am trying to connect that when I press the "calculate" button, it runs the calculations and generates data.

    As far as the range calculations, the inputs wouldn't be in between 0.19 and 0.20. The numbers that we input will only be in the tenths but you hit the nail on the head with the inequality calculations. But in this case I failed to mention that I am inserting the input number into a LineEdit and the output number is going to a LineEdit too. I don't feel as though QDoubleValidator will be necessary for any number over 1.10 is 25 so that basically covers all numerical ranges. I do appreciate that wisdom though because I was not aware of that option, same as the trigger based calculations that you had given above, I am sure they will be useful to me. Thank you so much for all of your help so far and I hope that my reply has explained some of the misconceptions. I appreciate all of your time and effort.

  4. #4
    Join Date
    Jan 2008
    Location
    Alameda, CA, USA
    Posts
    5,230
    Thanks
    302
    Thanked 864 Times in 851 Posts
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    I think if I were you I would redo the project as a QDialog-based app. If all you need is three line edits and a button, all of the mainwindow overhead is too much. If you intend to develop this into something more, maybe the mainwindow might be appropriate for the rewrite of the project. If you are just learning, I'd go for the simplest app possible.

    a - b = c

    c * 2 = sum (d)

    d / 0.9 = sum
    This still doesn't make sense as a set of consistent equations. What is "sum"? Is it a function taking an argument "d"? Is it a simple variable? If so, what does "sum( d )" mean mathematically? What are you summing? There's only a single value. And where does "d" come from in that case?

    You need to figure out your math before you can write code to compute it.

  5. #5
    Join Date
    Nov 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    Quote Originally Posted by d_stranz View Post
    You need to figure out your math before you can write code to compute it.
    Here is the full formula so there is no more confusion (Hopefully):

    Step 1: ppm Sulfur desired - ppm Sulfur from lab report = ppm Sulfur to be increased

    Step 2: ppm Sulfur to be increased * 2 = lbs actual S needed

    Step 3: lbs actual Sulfur needed / 0.9 = sum

    I was using the letters as simple variables because we have to link certain aspects of the formula to the next calculation so I figured it would be a good example to use.

    As far as the program is concerned, I will use just a QDialog to test out the theories until I build a better understanding, but yes, in the end I am bringing in a lot more calculations for each nutrient that we are amending so I will eventually be building a huge program, but not until I feel comfortable enough with the progress I make. Thank you for your help.

  6. #6
    Join Date
    Nov 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    Okay, I have been working for a few hours and here is what I have so far. It is a bit different from what you had. For background, I created buttons in the mainwindow.ui and they are labeled as follows: lineEditA, lineEditB, and lineEditSum. The button I used was a tool button and I named it calculateButton. Instead of doing all of that original formula, I am just trying to do a simple a - b = sum now just so I can get the hang of that and then work up from there. I am getting some errors while running this code. I will explain the errors after I show the code.

    mainwindow.h

    Qt Code:
    1. #ifndef MAINWINDOW_H
    2. #define MAINWINDOW_H
    3.  
    4. #include <QMainWindow>
    5.  
    6. namespace Ui {
    7. class MainWindow;
    8. }
    9.  
    10. class MainWindow : public QMainWindow
    11. {
    12. Q_OBJECT
    13.  
    14. public:
    15. explicit MainWindow(QWidget *parent = 0);
    16. ~MainWindow();
    17.  
    18. private slots:
    19.  
    20.  
    21. private:
    22. Ui::MainWindow *ui;
    23. void onCalculateClicked();
    24. void calculateAndDisplaySum();
    25. };
    26.  
    27. #endif // MAINWINDOW_H
    To copy to clipboard, switch view to plain text mode 
    main.cpp
    Qt Code:
    1. #include "mainwindow.h"
    2. #include <QApplication>
    3.  
    4. int main(int argc, char *argv[])
    5. {
    6. QApplication a(argc, argv);
    7. MainWindow w;
    8. w.show();
    9.  
    10. return a.exec();
    11. }
    To copy to clipboard, switch view to plain text mode 
    mainwindow.cpp
    Qt Code:
    1. #include <QLineEdit>
    2. #include <QToolButton>
    3. #include "mainwindow.h"
    4. #include "ui_mainwindow.h"
    5.  
    6. MainWindow::MainWindow(QWidget *parent) :
    7. QMainWindow(parent),
    8. ui(new Ui::MainWindow)
    9. {
    10. ui->setupUi(this);
    11. connect(ui->calculateButton, SIGNAL(clicked()), this, SLOT(onCalculateClicked()));
    12.  
    13. //onCalculateClicked(); -- Are these necessary?
    14. //calculateAndDisplaySum();
    15. }
    16.  
    17. MainWindow::~MainWindow()
    18. {
    19. delete ui;
    20. }
    21.  
    22. void MainWindow::onCalculateClicked()
    23. {
    24. calculateAndDisplaySum();
    25. }
    26.  
    27. void MainWindow::calculateAndDisplaySum()
    28. {
    29. double a = lineEditA->text().toDouble();
    30. double b = lineEditB->text().toDouble();
    31. double sum = a - b;
    32.  
    33. lineEditSum->setText(QString::number(sum, 'g', 2));
    34. }
    To copy to clipboard, switch view to plain text mode 
    mainwindow.ui
    Qt Code:
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <ui version="4.0">
    3. <class>MainWindow</class>
    4. <widget class="QMainWindow" name="MainWindow">
    5. <property name="geometry">
    6. <rect>
    7. <x>0</x>
    8. <y>0</y>
    9. <width>400</width>
    10. <height>300</height>
    11. </rect>
    12. </property>
    13. <property name="windowTitle">
    14. <string>MainWindow</string>
    15. </property>
    16. <widget class="QWidget" name="centralWidget">
    17. <widget class="QLineEdit" name="lineEditSum">
    18. <property name="geometry">
    19. <rect>
    20. <x>120</x>
    21. <y>10</y>
    22. <width>31</width>
    23. <height>20</height>
    24. </rect>
    25. </property>
    26. </widget>
    27. <widget class="QLineEdit" name="lineEditA">
    28. <property name="geometry">
    29. <rect>
    30. <x>10</x>
    31. <y>10</y>
    32. <width>31</width>
    33. <height>20</height>
    34. </rect>
    35. </property>
    36. </widget>
    37. <widget class="QLineEdit" name="lineEditB">
    38. <property name="geometry">
    39. <rect>
    40. <x>60</x>
    41. <y>10</y>
    42. <width>31</width>
    43. <height>20</height>
    44. </rect>
    45. </property>
    46. </widget>
    47. <widget class="QLabel" name="label">
    48. <property name="geometry">
    49. <rect>
    50. <x>50</x>
    51. <y>10</y>
    52. <width>16</width>
    53. <height>16</height>
    54. </rect>
    55. </property>
    56. <property name="text">
    57. <string>-</string>
    58. </property>
    59. </widget>
    60. <widget class="QLabel" name="label_2">
    61. <property name="geometry">
    62. <rect>
    63. <x>100</x>
    64. <y>10</y>
    65. <width>16</width>
    66. <height>16</height>
    67. </rect>
    68. </property>
    69. <property name="text">
    70. <string>=</string>
    71. </property>
    72. </widget>
    73. <widget class="QToolButton" name="calculateButton">
    74. <property name="geometry">
    75. <rect>
    76. <x>40</x>
    77. <y>40</y>
    78. <width>71</width>
    79. <height>19</height>
    80. </rect>
    81. </property>
    82. <property name="text">
    83. <string> Calculate</string>
    84. </property>
    85. </widget>
    86. </widget>
    87. <widget class="QMenuBar" name="menuBar">
    88. <property name="geometry">
    89. <rect>
    90. <x>0</x>
    91. <y>0</y>
    92. <width>400</width>
    93. <height>21</height>
    94. </rect>
    95. </property>
    96. </widget>
    97. <widget class="QToolBar" name="mainToolBar">
    98. <attribute name="toolBarArea">
    99. <enum>TopToolBarArea</enum>
    100. </attribute>
    101. <attribute name="toolBarBreak">
    102. <bool>false</bool>
    103. </attribute>
    104. </widget>
    105. <widget class="QStatusBar" name="statusBar"/>
    106. </widget>
    107. <layoutdefault spacing="6" margin="11"/>
    108. <resources/>
    109. <connections/>
    110. </ui>
    To copy to clipboard, switch view to plain text mode 
    Okay, so now that's out of the way, just in case you want to compile it in QtCreator5.5 yourself, the error messages only show up on the mainwindow.cpp and they are as follows:

    mainwindow.cpp:28: error: C2065: 'lineEditA' : undeclared identifier
    mainwindow.cpp:28: error: C2227: left of '->text' must point to class/struct/union/generic type
    type is 'unknown-type'
    mainwindow.cpp:28: error: C2228: left of '.toDouble' must have class/struct/union

    mainwindow.cpp:29: error: C2065: 'lineEditB' : undeclared identifier
    mainwindow.cpp:29: error: C2227: left of '->text' must point to class/struct/union/generic type
    type is 'unknown-type'
    mainwindow.cpp:29: error: C2228: left of '.toDouble' must have class/struct/union

    mainwindow.cpp:32: error: C2065: 'lineEditSum' : undeclared identifier
    mainwindow.cpp:32: error: C2227: left of '->setText' must point to class/struct/union/generic type
    type is 'unknown-type'

    That should be it. Sorry for all the information and bombardment of code. Thank you for all the help!

  7. #7
    Join Date
    Jan 2008
    Location
    Alameda, CA, USA
    Posts
    5,230
    Thanks
    302
    Thanked 864 Times in 851 Posts
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Simple Math Calculation Questions in QT (PyQt, Qt4 C++)

    Error #1 - move the declaration of your slot method (onCalculateClicked()) to the "private slots:" section of the MainWIndow class definition.

    Remaining errors all stem from the fact that "lineEditA", etc. are *not* member variables of your MainWindow class, but are member of the Ui::MainWindow class. This is a class automatically created by Qt's MOC (metaobject compiler) from your .ui file. It lives in the Ui namespace, which is why it is referenced as "Ui::MainWindow". Your own MainWindow constructor creates an instance of this Ui class (line 8 of mainwindow.cpp) and then initializes it (setupUi()) in the body of the constructor.

    Since all of the widget variables defined in your .ui file are public member variables of the Ui::MainWindow class, so to retrieve them from code in MainWindow, you have to go through the pointer to the Ui instance:

    ui->lineEditA->text(), etc.

    It is a good habit to learn to embed your child widgets in a layout of some sort so they will behave properly on resize. Your centralWidget doesn't use a layout, and you've hard-coded all of the child widget positions within it. While this may work in this case, it isn't good practice. It is good to get into the habit of putting a layout into every custom widget so that good things happen on resize, change of font, whatever.

    In this case, I would add a grid layout, and use horizontal and vertical spacers to push things into place. Here's your mainwindow.ui reworked with a grid layout and spacers:

    Qt Code:
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <ui version="4.0">
    3. <class>MainWindow</class>
    4. <widget class="QMainWindow" name="MainWindow">
    5. <property name="geometry">
    6. <rect>
    7. <x>0</x>
    8. <y>0</y>
    9. <width>445</width>
    10. <height>203</height>
    11. </rect>
    12. </property>
    13. <property name="windowTitle">
    14. <string>MainWindow</string>
    15. </property>
    16. <widget class="QWidget" name="centralWidget">
    17. <layout class="QGridLayout" name="gridLayout">
    18. <item row="0" column="5">
    19. <spacer name="horizontalSpacer">
    20. <property name="orientation">
    21. <enum>Qt::Horizontal</enum>
    22. </property>
    23. <property name="sizeHint" stdset="0">
    24. <size>
    25. <width>40</width>
    26. <height>20</height>
    27. </size>
    28. </property>
    29. </spacer>
    30. </item>
    31. <item row="0" column="4">
    32. <widget class="QLineEdit" name="lineEditSum"/>
    33. </item>
    34. <item row="1" column="2">
    35. <widget class="QToolButton" name="calculateButton">
    36. <property name="text">
    37. <string> Calculate</string>
    38. </property>
    39. </widget>
    40. </item>
    41. <item row="2" column="2">
    42. <spacer name="verticalSpacer">
    43. <property name="orientation">
    44. <enum>Qt::Vertical</enum>
    45. </property>
    46. <property name="sizeHint" stdset="0">
    47. <size>
    48. <width>20</width>
    49. <height>40</height>
    50. </size>
    51. </property>
    52. </spacer>
    53. </item>
    54. <item row="0" column="0">
    55. <widget class="QLineEdit" name="lineEditA"/>
    56. </item>
    57. <item row="0" column="1">
    58. <widget class="QLabel" name="label">
    59. <property name="text">
    60. <string>-</string>
    61. </property>
    62. </widget>
    63. </item>
    64. <item row="0" column="3">
    65. <widget class="QLabel" name="label_2">
    66. <property name="text">
    67. <string>=</string>
    68. </property>
    69. </widget>
    70. </item>
    71. <item row="0" column="2">
    72. <widget class="QLineEdit" name="lineEditB"/>
    73. </item>
    74. </layout>
    75. </widget>
    76. <widget class="QMenuBar" name="menuBar">
    77. <property name="geometry">
    78. <rect>
    79. <x>0</x>
    80. <y>0</y>
    81. <width>445</width>
    82. <height>26</height>
    83. </rect>
    84. </property>
    85. </widget>
    86. <widget class="QToolBar" name="mainToolBar">
    87. <attribute name="toolBarArea">
    88. <enum>TopToolBarArea</enum>
    89. </attribute>
    90. <attribute name="toolBarBreak">
    91. <bool>false</bool>
    92. </attribute>
    93. </widget>
    94. <widget class="QStatusBar" name="statusBar"/>
    95. </widget>
    96. <layoutdefault spacing="6" margin="11"/>
    97. <resources/>
    98. <connections/>
    99. </ui>
    To copy to clipboard, switch view to plain text mode 

    As you expand on this in Qt Designer, you add new widgets to the grid layout by clicking and dragging from Designer's "Widget Box" onto the form. The place where the widget will end up when you drop it will be highlighted by a red box (if you add it to an empty box in the grid) or a horizontal or vertical blue line if dropping it will expand the grid to add a new row or column of cells.

Similar Threads

  1. Few (hopefully) simple questions
    By QTGuy72 in forum Newbie
    Replies: 1
    Last Post: 10th July 2012, 18:30
  2. Simple questions
    By assismvla in forum Newbie
    Replies: 3
    Last Post: 2nd May 2010, 02:57
  3. may i ask questions related to pyqt here???
    By pyqt123 in forum Newbie
    Replies: 2
    Last Post: 14th December 2009, 07:28
  4. Two probably simple Qt4 Questions
    By frenk_castle in forum Newbie
    Replies: 3
    Last Post: 16th September 2009, 16:37
  5. Simple DB app, some questions.
    By juannm in forum Qt Programming
    Replies: 1
    Last Post: 19th February 2008, 12:46

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.