using one Qcombobox to set value to several labels, C++ - c++

im trying to set the value from a combobox to multiple Qlabels, the idea is to populate the QcomboBox with all the values, then according to the number, (ejem 15.6) the corresponding label should change the problem is, theres too many of them to simply use a switch of something similar, but all the names of the labels are similar, HumSec_val156 corresponds to 15.6 the main idea was to use
Silo* silo = new Silo;
QString number = widget.QComboBox->currentText();
QString nameOfLabel = "HumSec_val";
nameOfLabel.append(QString::number(number));
silo->findchild<QLabel*>(nameOfLabel)->setText(valuefromCombobox);
but everytime it simply return an empty string, i did try using somthing simplier like
widget.nameOfLabel->setText(valuefromComboBox);
but nameOfLabel its just a qstring so i can mix it with the code generated from designer. Any idea what can i do? do i need to create something like a scoped enum or similar?
below i add a picture of what im doing

If I would do something like this, I would probably create a QHash<QString, QLabel*> and use that as a cache to find the matching QLabel for each name.
Declaration:
QHash<QString, QLabel*> m_hash
Storing value:
m_hash[labelName] = labelPtr;
Reading value:
QLabel* labelPtr = m_hash.value(labelName, nullptr);
if (labelPtr)
{
// Access label
}
When you remove a label remember to remove it from the hash as well:
const QString key = m_hash.key(labelPtr);
m_hash.remove(key);

Related

1-indexed Model in QCombobox

I have a 1-indexed (readonly-)model and want to use it for a combobox.
I parse the data (comes from a file-parser) and have for example:
1: Variable Number 1 and that will be my first item, next
2: Variable Number 2 and so on.
When I click on an item the currentIndex()-method from QCombobox will give me a 0-indexed int, so my problem is:
I don't want to write everytime I parse a file +1 respectively -1 when writing back to the file (although the model is readonly, I can alter the data in the file). (I have nearly 30 UIs where I need the model, and for every UI I have to parse other data)
I currently use something like:
virtual int currentIndex() const { return QComboBox::currentIndex() + 1; }
virtual void setCurrentIndex(int index) { QComboBox::setCurrentIndex(index-1); }
I know that this is not ideal, because (set-)currentIndex is not virtual. But to avoid +/-1 I used this for now.
Does anybode have a good suggestion for this problem?
If you have a custom model you could add a role that returns the "real" index value.
If you just use strings to fill the combobox, you could use the setItemData() and itemData() methods to associated your reference value.
E.g.
comboBox->addItem("Number 1", 1);
and
int refValue = comboBox->itemData(comboIndex).toInt();
The associated data can be anything that can be stored in a QVariant.

How to change a color of QString item in QListView

I have a model of QListView and if I execute model->data(idx); it returns following Qvariant: QVariant(QString, "Colorful text"). Mine task is to edit the color of Colorful text.
I wanted to use smth like model->setData(idx, *dunno what put here*, Qt::EditRole);
I expect that I need to put color description in the place of *dunno what put here*, but I don't know how.
Can you help me?
In order to extract the text color from model->data(idx), you have use role Qt::ForegroundRole as an additional parameter to return a QVariant v.
Then you can check your QVariant objects value as an integer for example with
int c = v.value<int>();
Finally set your new, modified color back in the model via
v.setValue(c);
model->setData(idx, const QVariant & value, Qt::ForegroundRole);

How to use QlineEdit to enter integer values

I am trying to use QlineEdit.
How would I enter a value into the edit bar when I run the program and get that valued stored as a variable to be used later. So far I have only found out how to enter text using
void parameter_settings::on_lineEdit_textEdited(const QString &arg1)
{
ui->lineEdit->setText("");
}
I have a GUI that requires the user to enter a value within a specific range. That value would be stored as a variable for later use. I have read about validators but can't get it to work as intended.
I am not entirely sure what your question is, but you can get the input from a QLineEdit with the command text():
QString input = ui->lineEdit->text();
and an integer input by using:
int integer_value = ui->lineEdit->text().toInt();
As you mentioned validators: You can use validators to allow the user to insert only integers into the QLineEdit in the first place. There are different ones but I generally like to use 'RegEx' validators. In this case:
QRegExpValidator* rxv = new QRegExpValidator(QRegExp("\\d*"), this); // only pos
QRegExpValidator* rxv = new QRegExpValidator(QRegExp("[+-]?\\d*"), this); // pos and neg
ui->lineEdit->setValidator(rxv);
Note: As mentioned in the comments by Pratham, if you only require integers to be entered you should probably use a QSpinBox which does all this out-of-the-box and comes with extra handles to easily increase and decrease of the value.
Use this method:
QString str = QString::number(4.4);
ui->lineEdit->setText(str);

QDoubleValidator is not working?

I'm trying to apply validator in a line edit box in Qt 4.2 and it is not working:
QDoubleValidator *haha= new QDoubleValidator(this);
haha->setBottom(0.00);
haha->setDecimals(2);
haha->setTop(100.00);
get_line_edit()->setValidator(haha);
or
QDoubleValidator *haha= new QDoubleValidator(0.00,100.00,2,this);
Neither way, I can still enter what ever value I want.
But if I switch to QIntValidator, it works!
So I went onto Google and did a bit search, and many people used to having the same issue. Is it a bug? or there should be some other set up I should do?
Just tripped over this one. Try setting the QDoubleValidator notation to:
doubleValidator->setNotation(QDoubleValidator::StandardNotation);
The validator documentation says that it returns "Intermediate" from "validate" when the input is an arbitrary double but out of range.
You need to distinguish intermediate input and the final input the user wants to submit by use of a line edit control (e.g. by emitting the "returnPressed" signal). If the user typed "10000" that is still a valid intermediate input for a number between 0 and 100 because the user can prefix this input with "0.".
You have to set notation to your validator
QLineEdit *firstX;
QDoubleValidator* validFirstX = new QDoubleValidator(-1000, 1000, 3, ui.firstX);
validFirstX->setNotation(QDoubleValidator::StandardNotation);
then it works but not fully correct. Interesting part is that it controls the digit numbers not number itself. For example, In this example, you can enter to QLineEdit 1000 either 9999.
&& ( input.toDouble() > top() || input.toDouble() < bottom())
This example works fine in 4.8. It doesn't look like its changed since 4.2 so I suspect the problem lies in how you are creating your QLineEdit. This is the relevent code from that example.
QLineEdit* validatorLineEdit;
validatorLineEdit = new QLineEdit;
validatorLineEdit->setValidator( new QDoubleValidator(-999.0, 999.0, 2, validatorLineEdit));
How have you created your line edit?
To clarify, use QDoubleValidator::setNotation(QDoubleValidator::StandardNotation)
Example:
QDoubleValidator* doubleValidator = new QDoubleValidator(-999.0, 999.0, 2, validatorLineEdit);
doubleValidator->setNotation(QDoubleValidator::StandardNotation);
validatorLineEdit->setValidator(doubleValidator);
If you set a validator to a QLineEdit then you can use the function hasAcceptableInput() to check whether inputed value is valid or invalid. For example:
if (!ui->lineEdit_planned_count_vrt->hasAcceptableInput())
{
slot_show_notification_message("EDIT_PLAN_COUNT_VRT", notification_types::ERROR, INVALID_INPUTED_VALUE);
return;
}
bool isOk = false;
double value = ui->lineEdit_planned_count_vrt->text().toDouble(&isOk);
//do something with the value here....

How do I access a member tab of a QTabWidget class by using a variable name?

In a function I am currently working on, I am creating a multi-dimensional array of checkboxes, with the dimensions specified at run-time by the user. In order to represent the 'z' dimension, I create multiple tabs -- each one representing a different dimension -- and create an array of check boxes in each tab. The tabs are labeled dim1, dim2, dim3, ... etc.
The problem I am having is the fact that in order to create the array of check boxes (within 3 'for' loops), I have to call the tabs as follows:
checkBoxVector.append(new QCheckBox( ui->dim1 ));
Where checkBoxVector holds pointers to the checkboxes. Now my first thought was that I would simply create a variable name that would change with each loop. With each iteration, it would go: "dim1", then "dim2", "dim3", ... etc. The problem with this is that I cannot reference the tabs with a string variable, I must type in the actual name of the tab. Here is a sample of that code:
int num = k+1;
QString dim = "dim";
QString tab_name = dim.append(QString("%1").arg(num));
checkBoxVector.append(new QCheckBox( ui->tab_name ));
This gives me the error " 'class Ui::MainWindow' has no member named 'tab_name' ".
Therefore; my question is: how can I apply this idea of changing the NAME of the tab with each loop, without causing such an error?
EDIT: I think I forgot to mention that the tabs have already been created at this point, and have already been labeled with the "dim1", "dim2", "dim3", ... names. The only issue I am having is how to reference these tabs after they have been created. I feel like there is a simple syntax solution.
Store the pointers to tabs in an array and index it with the variable that you use for iterating over the third dimension of your multidimensional array of checkboxes, your code would look something like this:
QTabWidget* tabs[3];
tabs[0] = ui->dim1;
tabs[1] = ui->dim2;
tabs[2] = ui->dim3;
// ... and then
checkBoxVector.append(new QCheckBox( tabs[z] ));
Someone will say it better (there is a concept name for that) but you can't dynamically declare members in c++ ... if you want QString tab_name content to be in any way related to a member of ui in this part of code:
QString tab_name = dim.append(QString("%1").arg(num));
checkBoxVector.append(new QCheckBox( ui->tab_name ));
The compiler need to know at compile time witch member of ui it will use to find the parent of the the new QCheckBox.
Correct me if I am wrong, you have dimz tabs and dimy*dimx QcheckBox in each tabs. You don't know any dim* when you build you ui file ?
So create your own widget (QWidget) it will store an array of QcheckBox* that you can dynamically create in constructor for example. This widget will take care of the proper layout of the check boxes.
Then finally you create you own QTabWidget that will create dimz tabs of your widget. You will access your tabs with their indexes corresponding to their z coordinate.
You're trying to reference a member variable that does not exist:
int num = k+1;
QString dim = "dim";
QString tab_name = dim.append(QString("%1").arg(num));
checkBoxVector.append(new QCheckBox( ui->tab_name ));
The error is caused by the fact that you are passing a non-existing member variable to the constructor of QCheckBox. The object the ui pointer is pointing to has no member variable named tab_name. If I understood your description correctly, just pass the local variable tab_name to the QCheckBox constructor like this:
checkBoxVector.append(new QCheckBox( tab_name ));