PDA

View Full Version : changing QPushButton label



Ferric
31st January 2010, 05:34
Hi,

I am trying to find a way to change the text displayed on a button, currently I have created a button:


QPushButton *uploadButton = new QPushButton(tr("Upload To Unit number one"));

and once I have clicked this button, I would like the button label to be changed to something like


"Upload To Unit number two"


I know I can use something like:


uploadButton->setText("upload to unit number two");

But when I put this in a slot that is activated by the signal emitted by the uploadButton, my application just quits,

I think maybe I have to declare the uploadButton as a "Global" widget( if you know what I mean), but I'm not sure how to do this..


Any advice appreciated, Thanks

franz
31st January 2010, 08:04
Put it in your class definition:

class YourWidget : public QWidget {
public:
YourWidget();
virtual ~YourWidget();

protected slots:
void updateTexts();

private:
QPushButton *m_pushButton;
};

void YourWidget::updateTexts()
{
m_pushButton->setText("New text");
}

Another possibility is, since you know what is calling the function:


void YourWidget::updateTexts()
{
QPushButton *caller = qobject_cast<QPushButton *>(sender());
if (!caller) // caller is NULL if sender() cannot be cast to the requested type.
return;
caller->setText("New text");
}

Ferric
31st January 2010, 09:11
I did the following as suggested,

In the header file:


protected slots:

void updateTexts();


private:

QPushButton *m_pushButton;

In the source file:


void YourWidget::updateTexts()

{

m_pushButton->setText("New text");

}


Then I attached the button signal to the updateTexts() slot, my program built and ran, but when I clicked the button, windows just says "myprogram.exe has encountered a problem and needs to close. We are sorry for the inconvenience."

I might try getting this concept working on a simple example first, basically if I can find a button that updates its own label every time its clicked I should be able to work backwards to implement it in my program. If anyone can think of a concept like this in any of the Qt Examples that are included with Qt creator please let me know.

Ferric
31st January 2010, 09:57
Aha, I got it, I just had to create the button in the following manner:


uploadButton = new QPushButton;