I have a QPushButton, this button has a text on it, this text is a number. In a slot of another object i want to change number that displayed on button, but when i call
MyButton->setText(QString("%1").arg(Number));
or
QString tmp;
tmp.setNum(Number);
MyButton->setText(tmp);
text on button dosen't changes.
But when i call
MyButton->setText("some random text");
it works fine.
How i can change number that displaying on button?
Part of my code:
sortWindow::sortWindow(QWidget *parrent)
{
...
MyButton = new QPushButton;
QString tmp(QString("%1").arg(Number));
MyButton.setText(tmp);
...
}
and
void sortWindow::workOnSignal(int index)
{
...
if (something)
{
...
QString tmp;
tmp.setNum(Number);
MyButton->setText(tmp);
...
}
Type of Number must be int. So it will work properly.
#include <QApplication>
#include <QPushButton>
int main(int argc,char **argv)
{
QApplication app(argc,argv);
QPushButton *pd = new QPushButton;
pd->setText(QString("%1").arg(1234));
pd->show();
return app.exec();
}
Related
I edited it like this. But all text is not printed in textEdit even though the word is added to the correct position and colored.
ui->textEdit->setText(display_text);
QTextcursor cursor=ui->textEdit->textCursor();
cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor,cursor_position);
cursor.insertHtml("<span style=color:red;>"+coloring_string+"</span>");
ui->textEdit->setTextCursor(cursor);
You have to use setExtraSelections:
#include <QApplication>
#include <QTextEdit>
class Editor: public QTextEdit {
public:
Editor(QWidget *parent=nullptr): QTextEdit(parent){
connect(this, &QTextEdit::cursorPositionChanged, this, &Editor::highlightCurrentLine);
highlightCurrentLine();
}
private:
void highlightCurrentLine(){
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor("red");
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
setExtraSelections(extraSelections);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle("fusion");
Editor editor;
editor.resize(640, 480);
editor.show();
return a.exec();
}
I have a class called UserInterface. In this class there are different functions. build_start_screen() adds all the widgets (labels, buttons,...) for the initial startscreen. build_option_a_screen() removes everything from the startscreen and adds all the widgets needed for the screen when the users click on the button for option A, and so on. The class is stripped down for the sake of this question.
Now I have declared a button in build_start_screen() and connected it to a simple MessageBox.exec() so it should pop-up on click.
However, nothing happens when the button gets clicked.
What am I doing wrong? Has it something to do with the lifetime of variables expiring after the function finishes?
#include <QApplication>
#include <QPushButton>
#include <QAbstractButton>
#include <QLabel>
#include <QFont>
#include <QVBoxLayout>
#include <QMessageBox>
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
//Test messagebox
QMessageBox msgBox;
msgBox.setText("Button test.");
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QAbstractButton::connect(showMsgBox, SIGNAL (clicked()), &window, SLOT (msgBox.exec()));
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
private:
//Properties
QVBoxLayout* layout;
};
int main(int argc, char **argv) {
QApplication app (argc, argv);
//Initialize Window
QWidget Window;
Window.resize(400, 250);
//Create new UserInterface object
//This will allow us to create different user-interfaces
//depending on the function we call
UserInterface* ui = new UserInterface();
ui->build_start_screen(Window);
Window.show();
return app.exec();
}
And what if I'd like to do the same, but instead of calling a messageBox I'd like to call another function?
#include <QApplication>
#include <QPushButton>
#include <QAbstractButton>
#include <QLabel>
#include <QFont>
#include <QVBoxLayout>
#include <QMessageBox>
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
//Test messagebox
QMessageBox msgBox;
msgBox.setText("Button test.");
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QAbstractButton::connect(showMsgBox, SIGNAL (clicked()), &window, SLOT (build_option_a_screen()));
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
void build_option_a_screen(QWidget& window) {
//Do stuff here with window
//e.g
window.resize(500, 500);
}
private:
//Properties
QVBoxLayout* layout;
};
int main(int argc, char **argv) {
QApplication app (argc, argv);
//Initialize Window
QWidget Window;
Window.resize(400, 250);
//Create new UserInterface object
//This will allow us to create different user-interfaces
//depending on the function we call
UserInterface* ui = new UserInterface();
ui->build_start_screen(Window);
Window.show();
return app.exec();
}
Your code has 2 problems:
The window "object" does not have slot "msgBox.exec()" as pointed out by the error:
QObject::connect: No such slot QWidget::msgBox.exec() in ../main.cpp:23
Correcting the above, the solution would be:
QObject::connect(showMsgBox, &QPushButton::clicked, &msgBox, &QMessageBox::exec);
but now the problem is that "msgBox" is a local variable that will be destroyed and cannot be displayed.
So the solution is to make msgBox a member of the class or a pointer (in the case of the pointer you must manage the dynamic memory to avoid memory leaks):
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
msgBox.setText("Button test.");
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QObject::connect(showMsgBox, &QPushButton::clicked, &msgBox, &QMessageBox::exec);
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
private:
//Properties
QVBoxLayout* layout;
QMessageBox msgBox;
};
Plus:
It is recommended not to use the old connection syntax as it has limitations and hides the problems.
It is recommended not to use the old connection syntax as it has limitations and hides the problems.
If you want to connect to a method of some kind that is not a QObject (for example X as you want the OP) then the solution is to use a lambda method:
//Class handling all the UI in this Application
class UserInterface {
public:
//Build the initial UI the user sees
void build_start_screen(QWidget& window) {
//Make new QVBoxLayout for this startscreen UI
this->layout = new QVBoxLayout(&window);
//Button to go to Option A-screen
QPushButton* showMsgBox = new QPushButton("Show pop-up");
QObject::connect(showMsgBox, &QPushButton::clicked, [this, &window](){
build_option_a_screen(window);
});
//Add labels and button to QVBoxLayout
layout->addWidget(showMsgBox);
}
void build_option_a_screen(QWidget& window) {
//Do stuff here with window
//e.g
window.resize(500, 500);
}
private:
//Properties
QVBoxLayout* layout;
};
My program should:
collect some input from QLineEdits;
convert it into QStrings;
add it to some QStrings which are constant;
output the whole stuff in a QTextEdit when a button is clicked.
Below is the simplified model of the program. It can be compiled; I get no errors; however, it doesn't do what I need. It just fails to output and I have really no idea why. I've struggled too hard to get it show no errors and now I've run out of ideas. Can anybody help me please?
#include <QtGui>
#include <QtCore>
class MyObject : public QObject
{
Q_OBJECT
public:
QTextEdit text;
QString c;
public slots:
void onClicked() {
text.setText(c);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget mw;
mw.setWindowTitle("Main Window");
mw.resize(400, 400);
mw.show();
QLabel label ("Enter something:", &mw);
label.setAlignment(Qt::AlignHCenter);
label.show();
QLineEdit line (&mw);
line.show();
QString a = line.text();
QString b = "This line is to be added";
QString c = a+b;
QTextEdit text (&mw);
text.show();
QPushButton btn ("Convert", &mw);
MyObject obj;
QObject::connect(
&btn,
SIGNAL(clicked()),
&obj,
SLOT(onClicked()));
btn.show();
QVBoxLayout layout_mw;
layout_mw.addWidget(&label);
layout_mw.addWidget(&line);
layout_mw.addWidget(&btn);
layout_mw.addWidget(&text);
mw.setLayout(&layout_mw);
return app.exec();
}
#include "sample.moc"
According to the code you provide it seems that you do not know that:
Qt works asynchronously, for example the value of a that you get is before the window is displayed, what value will it have? Well, it will have an empty string, so at what moment should I ask for the text? right in the slot that is called when the button is pressed.
Variables with the same name do not imply that they are the same, for example you have 2 QTextEdit with the name of text, these are different objects.
So as you realize the objects (widgets) must have the same scope to be able to interact with each other, so I will create a class that inherits from QWidget and that has the other elements as attributes.
#include <QtGui>
#include <QtCore>
class Widget: public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent=nullptr):
QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(&label);
layout->addWidget(&line);
layout->addWidget(&button);
layout->addWidget(&textedit);
label.setText("Enter something:");
label.setAlignment(Qt::AlignHCenter);
button.setText("Convert");
connect(&button, SIGNAL(clicked()), this, SLOT(onClicked()));
}
private slots:
void onClicked(){
QString a = line.text();
QString b = "This line is to be added";
QString c = a+b;
textedit.setText(c); // or textedit.append(c);
}
private:
QLabel label;
QLineEdit line;
QPushButton button;
QTextEdit textedit;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Widget w;
w.show();
return app.exec();
}
#include "sample.moc"
Im trying to simply display of 2 different QTextEdit value into a QLabel. I have tried for a single QTextEdit but couldn't display the value of both QTextEdit.
void MainWindow::on_pushButton_clicked()
{
ui->label_az->setText(ui->textEdit_ra1->toPlainText());
ui->label_az->setText(ui->textEdit_ra2->toPlainText());
}
It doesn't display the QTextEdit values when I click on pushbutton. Thank you in advance
Just to summarize our comments into a single post: QLabel::setText replaces the content of the label, so you have to create the whole string before and set it once. Code below will do it:
void MainWindow::on_pushButton_clicked()
{
ui->label_az->setText(
ui->textEdit_ra1->toPlainText() +
" " + // use here the separator you find more convenient
ui->textEdit_ra2->toPlainText());
}
The second setText() call replaces the label's text. You want to combine both texts into a single label text, like this:
label->setText(text_1->toPlainText() + "\n" + text_2->toPlainText());
Here's a complete example program, to give context:
#include <QWidget>
#include <QBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QLabel>
#include <QApplication>
#include <memory>
int main(int argc, char **argv)
{
QApplication app{argc, argv};
const auto w = std::make_unique<QWidget>();
const auto window = w.get();
const auto layout = new QVBoxLayout(window);
const auto text_1 = new QTextEdit(window);
layout->addWidget(text_1);
const auto text_2 = new QTextEdit(window);
layout->addWidget(text_2);
const auto button = new QPushButton("Push Me!", window);
layout->addWidget(button);
const auto label = new QLabel(window);
layout->addWidget(label);
QObject::connect(button, &QPushButton::pressed,
label, [=]() { label->setText(text_1->toPlainText() + "\n" + text_2->toPlainText()); });
window->show();
return app.exec();
}
Under Windows, I've seen a nice feature: If I hover with the mouse over a short text field which contains overlong text not fitting completely into the field, a tooltip opens, displaying the complete contents of the text field.
Can someone point me to a code snippet which does this with QLineEdit?
I would create a custom class derived from QLineEdit like so:
#ifndef LINEEDIT_H
#define LINEEDIT_H
#include <QtGui>
class LineEdit : public QLineEdit
{
Q_OBJECT
public:
LineEdit();
public slots:
void changeTooltip(QString);
};
LineEdit::LineEdit()
{
connect(this, SIGNAL(textChanged(QString)), this, SLOT(changeTooltip(QString)));
}
void LineEdit::changeTooltip(QString tip)
{
QFont font = this->font();
QFontMetrics metrics(font);
int width = this->width();
if(metrics.width(tip) > width)
{
this->setToolTip(tip);
}
else
{
this->setToolTip("");
}
}
#include "moc_LineEdit.cpp"
#endif // LINEEDIT_H
Then just add it to whatever:
#include <QtGui>
#include "LineEdit.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
LineEdit edit;
edit.show();
return app.exec();
}
Here the improved function as mentioned in the comments above.
void LineEdit::changeTooltip(QString tip)
{
QFont font = this->font();
QFontMetrics metrics(font);
// get the (sum of the) left and right borders;
// note that Qt doesn't have methods
// to access those margin values directly
int lineMinWidth = minimumSizeHint().width();
int charMaxWidth = metrics.maxWidth();
int border = lineMinWidth - charMaxWidth;
int lineWidth = this->width();
int textWidth = metrics.width(tip);
if (textWidth > lineWidth - border)
this->setToolTip(tip);
else
this->setToolTip("");
}
You can try to change the tooltip each time the text is changed:
First, define a private slot to react the textChanged() signal from the QLineEdit:
(in the header file from the class where your QTextEdit belongs)
....
private slots:
void onTextChanged();
....
In the cpp file, then, connect the QLineEdit textChanged() signal to the slot you defined, and implement the behavior when the text changes:
// In constructor, or wherever you want to start tracking changes in the QLineEdit
connect(myLineEdit, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
Finally, this is how the slot would look like:
void MainWindow::onTextChanged() {
myLineEdit->setTooltip(myLineEdit->text());
}
I'm supposing a class called MainWindow contains the QLineEdit.