How to get the text on qpushbutton? - qt

I am loading .ui files via QUiloader, and showing the GUI in my application.
QWidget *mywidget = loader.load(file, this);
QList<QWidget*> wlist = mywidget.findChildren<QWidget *>()
I would like to know what is the text on QPushbutton. I know there is a method text() to get a text from Pushbutton, but it is not accessible when I do:
QString btext = wlist.at(1).text();
Any idea how I can get the text from QPushbutton, and other Widgets, when they grouped as QWidget?
Thanks.

You should search for QPushButtons instead of QWidgets:
QList<QPushButton*> blist = widget.findChildren<QPushButton*>();
Still your code wouldn't compile. The last line should read:
QString btext = blist.at(1)->text();
Using -> since you are accessing a pointer, not the widget. Also you should check if the findChildren() function actually returnes enough buttons. You would get a crash or assertions when accessing a list item by an invalid index.
Also please note that at(1) does not return the first but the second item in the list (lists start from 0).
Update: If you search for QWidgets and cast each of them you need to take care of getting a nullptr:
QList<QWidget*> wlist = widget.findChildren<QWidget*>();
foreach (QWidget* w, wlist)
{
QPushButton* b = dynamic_cast<QPushButton*>(w);
// If "w" is not a button "b" is nullptr
if (b)
{
QString btext = b->text();
}
}

Related

Application crashing when searching for QLineEdit in QFormLayout

I've experienced a weird crash when trying to find a QLineEdit in a QFormLayout.
Firstly, I created a QFormLayout and set a name for it:
QFormLayout *charColLayout = new QFormLayout; charColLayout->setObjectName("charColLayout");
Then, I created a QLineEdit, modified it a bit and add it in to the layout, and I also give it a name:
QLineEdit *delim = new QLineEdit;
delim->setMaxLength(1);
delim->setMaximumWidth(100);
delim->setText("/");
delim->setObjectName("delEdit");
charColLayout->addRow("Delimiter", delim);
Afterward, in a completely different function, I re-searched that layout with findChild():
QFormLayout *charcoal = secondHoriField->findChild<QFormLayout *>("charColLayout", Qt::FindChildrenRecursively);
It should be noted that secondHoriField is just a normal QLayout which my QFormLayout is located in.
Finally, I attempted to find that QLineEdit:
QLineEdit *delimEdit = charcoal->findChild<QLineEdit*>("delEdit", Qt::FindChildrenRecursively);
if (delimEdit == nullptr) {cerr << "error\n";} //debug
string curDelim = qStrToStr(delimEdit->text());
And it surprisingly came down with a crash, and as the output shown, it's because the delimEdit is null.
18:06:10: Starting D:\...\build-cryptog-Desktop_Qt_5_15_2_MinGW_64_bit-Debug\debug\cryptog.exe ...
error
18:06:17: The program has unexpectedly finished.
18:06:17: The process was ended forcefully.
18:06:17: D:\...\build-cryptog-Desktop_Qt_5_15_2_MinGW_64_bit-Debug\debug\cryptog.exe crashed.
But when I switched the findChild() function for this rather bruteforce-y line:
QLineEdit *delimEdit = dynamic_cast<QLineEdit*>(charcoal->itemAt(1)->widget());
cerr << qStrToStr(delimEdit->objectName()) << endl; //debug line
The program ran fine, and it showed the same name I set for the QLineEdit:
18:12:02: Starting D:\...\build-cryptog-Desktop_Qt_5_15_2_MinGW_64_bit-Debug\debug\cryptog.exe ...
delEdit
18:12:11: D:\...\build-cryptog-Desktop_Qt_5_15_2_MinGW_64_bit-Debug\debug\cryptog.exe exited with code 0
Why did this happened?
Another note: qStrToStr() is a function I implement to convert QString to std::string, and I have hand-checked it.
While findChild is a QObject method the itemAt is a QFormLayout method.
QObject::findChild
QFormLayout::itemAt
With addRow you add an item to the QFormLayout. This does not make it a child in the context of the QObject.
QFormLayout::addRow
The purpose of the QFormLayout is to organize the positioning of QWidgets, it is not meant to serve as a container. Maybe you could check whether the top level QWidget (e.g. QMainWindow) holding the QFormLayout would be a better choice as a parent for the QLineEdit.
Assuming you have some kind of QMainWindow:
QMainWindow myMainWindow;
// ...
QLineEdit *delim = new QLineEdit(&myMainWindow);
delim->setObjectName("delEdit");
//...
In another location:
auto delimEdit = myMainWindow.findChild<QLineEdit*>("delEdit");

Processing signal of QTreeWidget that has QTreeWidgetItem derivitives as items

I didn't find a proper solution to this problem, so I hope somebody can give me an answer to my problem:
I am using a normal QTreeWidget, but as items I use an own subclass of QTreeWidgetItem (because I needed to store some other information in the item). Now I want to use the itemClicked() signal by the QTreeWidget, but I think my slot doesn't get any signal and I think it has to do with the signature of itemClicked(), since it sends a QTreeWidgetItem and of course not my own subclass.
Is it possible that QTreeWidget doesn't detect a click on my own subclass items?
Here is my connection:
connect(treeWidget, SIGNAL(itemClicked(QTreeWidgetItem *)), this, SLOT(displayTransformData(QTreeWidgetItem*)));
And here is my slot:
void GUI::displayTransformData(QTreeWidgetItem* item) {
cout << "test" endl;
Q_actorTreeWidgetItem* actor_item = dynamic_cast<Q_actorTreeWidgetItem*>(item);
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor = actor_item->getActorReference();
double* position = new double[3];
position = actor->GetOrigin();
x_loc->setText(QString(std::to_string( position[0]).c_str() ));
}
I'm already trying to cast the item that I could get from the signal into my own subclass, but the slot function is never called, because the test from my cout line doesn't appear in the console.
I'm very grateful for every help!
The problem is your incorrect SIGNAL specification,
SIGNAL(itemClicked(QTreeWidgetItem *))
You should probably see a warning message at the console along the lines of:
QObject::connect: No such signal
tree_widget::itemClicked(QTreeWidgetItem *) in ...
From the documentation the actual signal spec is
void QTreeWidget::itemClicked(QTreeWidgetItem *item, int column)
So, using the old Qt4 syntax you need
connect(treeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
this, SLOT(displayTransformData(QTreeWidgetItem*)));
If possible, however, you should make use of the newer Qt5 signal/slot syntax
connect(treeWidget, &QTreeWidget::itemClicked, this, &GUI::displayTransformData);

Can a QComboBox display a different value than whats in it's list?

Using Qt 5.9 on Linux, I have a QComboBox with several labels.
qc = new QComboBox;
qc->addItem(tr("Red"));
qc->addItem(tr("Green"));
qc->addItem(tr("Blue"));
Lets say a user activates the QComboBox and the 3 color labels are shown in the drop down list. The user then selects the 1st item (red).
What I want to do is have the QComboBox display a different value than what was selected. I.e., if red is selected, then a number is shown, possibly 1 for the first item (or it could be an R for Red), and if green is selected, then display 2 (or G) for the second item.
My goal in doing this is to use less display space (less wide) than is actually necessary to show the complete text of the selection because some of my item strings are quite long and a much shorter label is desired when the QComboBox is not activated in it's drop down state. Besides, the item strings are descriptive and abbreviations would work better for displaying.
Edit:
Using Marek's example, thought this might help. Here's what I have. I'm expecting if the user selects from the list, then an R, G, or a B should be displayed after.
QStandardItem *red = new QStandardItem();
red->setData(tr("Red"), Qt::DisplayRole);
red->setData("R", Qt::UserRole);
QStandardItem *green = new QStandardItem();
green->setData(tr("Green"), Qt::DisplayRole);
green->setData("G", Qt::UserRole);
QStandardItem *blue = new QStandardItem();
blue->setData(tr("Blue"), Qt::DisplayRole);
blue->setData("B", Qt::UserRole);
QStandardItemModel *rgb_model = new QStandardItemModel(this);
rgb_model->setItem(0, red);
rgb_model->setItem(1, green);
rgb_model->setItem(2, blue);
QComboBox *rgb_cb = new QComboBox();
rgb_cb->setModel(rgb_model);
I get the feeling it's because I don't quite understand how to use Qt::UserRole.
Yes it is possible. QComboBox uses data model to manage items.
You have to provide own data model, with items with respective data values.
QStandardItem *itme1 = new QStandardItem();
item1->setData(tr("Red"), Qt::DisplayRole);
item1->setData("1", Qt::UserRole); // note doesn't have to be a string.
QStandardItem *itme2 = new QStandardItem();
item2->setData(tr("Green"), Qt::DisplayRole);
item2->setData("2", Qt::UserRole);
QStandardItemModel *model = new QStandardItemModel(this);
mode->setItem(1, item1);
mode->setItem(2, item2);
qc->setModel(model);
It should work, but I didn't test it. At least this should be some clue.
Please review QComboBox documentation, especially about roles.
Another solution is use translations with multiple lengths. You can provide couple translation for a single string. Each translation should be graphically shorter than earlier one.
In such situation QString contains all possibilities separated by spatial character. When such string is rendered first substring (between separators) which will fit available space will be used.
Now I do not remember what is the separator value. I've used this very long time ago (with Qt 4.8) and now can't find reference for it.
In your example for make it short just make:
qc->setWidth( 20 );
But if you really want user choose something, then:
connect( qc, SIGNAL( onCurrentIndexChanged( int ) ), SLOT( changeComboText() ) );
[...]
void changeComboText()
{
QString shortText;
//Determine short value for shortText
qc->setCurrentText( shortText );
}

How to get the text of a combobox in a tablewidget?

I’m new to Qt, I need help with getting the value of a combobox in a table widget.
I use “setCellWidget” to add a combobox(in my case, its name is “settingA”) to a table widget (the name is “tableWidget_4”):
QComboBox* settingA = new QComboBox();
settingA->addItem("100");
settingA->addItem("200");
ui->tableWidget_4->setColumnCount(1);
ui->tableWidget_4->setRowCount(3);
ui->tableWidget_4->setCellWidget ( 0, 0, settingA );
What I want to do here is:
When a button (its name is “ApplyComboButton” in my case) is clicked, I want the value of the combobox(settingA) can be saved into a QStringList(InputComboData) , and this is how I try to do this:
void MainWindow::on_ApplyComboButton_clicked()
{
QStringList InputComboData;
InputComboData << ui->tableWidget_4->item(0,0)->text();
}
And it fails.
How can I get the value of my combobox?
You can use the QTableWidget::cellWidget ( int row, int column ) function to get your QComboBox widget. Use qobject_cast to cast it to QComboBox, and use the currentText() function to get the text.
QComboBox *myCB = qobject_cast<QComboBox*>(ui->tableWidget_4->cellWidget(0,0));
InputComboData << myCB->currentText();
Use QTableWidget's cellWidget to get a QWidget* to the widget you set as cellWidget (don't forget to use qobject_cast or dynamic_cast to cast that pointer to a QCombobox*)

How to make QPushButtons to add text into QLineEdit box?

I used Qt Creator to make a "keyboard" window with sixty QPushButtons and one QLineEdit. How can I make the buttons to add characters into QLineEdit text box? If I press a QPushButton with the label 'Q' on it, I want the program to add the Unicode character 'Q' on the text box.
One way to do this would be to just connect the 'clicked' signal from all the buttons to a slot, and then handle the adding of the character there.
For example, if the all keyboard buttons are inside a layout called 'buttonLayout', in your MainWindow constructor you can do this:
for (int i = 0; i < ui->buttonLayout->count(); ++i)
{
QWidget* widget = ui->buttonLayout->itemAt( i )->widget();
QPushButton* button = qobject_cast<QPushButton*>( widget );
if ( button )
{
connect( button, SIGNAL(clicked()), this, SLOT(keyboardButtonPressed()) );
}
}
Then in the slot implementation, you can use QObject::sender(), which returns the object that sent the signal:
void MainWindow::keyboardButtonPressed()
{
QPushButton* button = qobject_cast<QPushButton*>( sender() );
if ( button )
{
ui->lineEdit->insert( button->text() );
}
}
OPTION 1 - Multiple signals and slots
Connect all pushbuttons clicked() signal to a slot
// Let button01 be the A
connect(ui->button01, SIGNAL(clicked()), this, SLOT(buttonClicked()));
...
// Let button 60 be the Q
connect(ui->button60, SIGNAL(clicked()), this, SLOT(buttonClicked()));
In the buttonClicked() slot you have to figure out which button was clicked and append the corresponding letter to the line edit.
void buttonClicked()
{
QObject* callingButton = QObject::sender();
if (callingButton == button01)
ui->lineEdit->setText(ui->lineEdit->text()+ "A");
...
else if (callingButton == button60)
ui->lineEdit->setText(ui->lineEdit->text()+ "Q");
}
OPTION 2 - Subclass QPushButton
You could subclass QPushButton in order to avoid the multiple ifs. In your subclass just catch the mouse release event and emit a new signal which will contain the button's text
void KeyboardButton::mouseReleaseEvent(QMouseEvent* event)
{
emit clicked(buttonLetter); // Where button letter a variable of every item of your subclass
}
Similarly connect the clicked(QString) signal with a slot
connect(ui->button01, SIGNAL(clicked(QString)), this, SLOT(buttonClicked(QString)));
...
connect(ui->button60, SIGNAL(clicked(QString)), this, SLOT(buttonClicked(QString)));
void buttonClicked(QString t)
{
ui->lineEdit->setText(ui->lineEdit->text()+ t);
}
I have created an application with a similar issue, trying to convert the qpushbutton text to the qlineedit itself. The key is how you initialize the buttons and to use polymorphism in your function. To create an emit signal wont work for individual characters. The .digitValue will work if the case if for numerics (which the buttons would be of type int), but qt doesnt have a character value (I should say after 6hrs of reading qt doc and another 4 of trying different combinations it would not work), I think it has to do with how many bits it takes to store each variable type in an array. I even tried converting the button->text to QString to use with the emit function as a signal prototyped.
I do not know what your button layout is, but I will give you a synopsis of what I did. I first created a global, static const char array containing all the letters needed e.g.
static const char vowelarray[] = "AEIOU";
Then initialized the QPushButtons with in the MainWindow function, using iteration, setting a for loop's terminating condition equal to the size char array (in your case 60?). This all depends on your button layout though. I personally created a void function (setLocation) for the button->setGeometry of each button and iterated the setGeometry, and then passed the function to the MainWindow Function, at end of fucntion. The following code was used to initialize the buttons, connect signals to slots, and use polymorphism to connect to lineedit.
for (int i = 0; i < 26; i++){
characterButton[i] = new QPushButton(chararry[i], this); `
characterButton[i] -> setStyleSheet("QPushButton{background: grey; color: brown}");
connect(characterButton[i],SIGNAL(released(),this,SLOT(characterPushed()));
}
setLocation();
Then created a void function (e.g. void MainWindow::characterPuched()) where the following code was used:
void MainWindow::characterPushed(){
QPushButton *characterButton = (QPushButton*) sender();
if (characterButton )
{
lineEdit -> setText(letters.insert(letters.size(), characterButton -> text()));
}
lineEdit -> setText(letters);
}
of course letters was a global variable as well as:
QString letters = "";
and of course the QPushButtons and the function were prototype in the header file as a private variables and slots, e.g.
private:
QPushButton *characterButton[26];
the variable 'letters' was used to extract and input text to and from the line edit for further functions throughout the application.
Best Luck!!``

Resources