开发者

Add text to QTextEdit using QPushButton

Just a simple program to add text to textedit when button is clicked... anyt开发者_开发知识库hing wrong here??


#include<QPushButton>
#include<QApplication>
#include<QTextEdit>
#include<QWidget>
#include<QHBoxLayout>
#include<QLabel>

int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QHBoxLayout *layout=new QHBoxLayout;
QTextEdit *text = new QTextEdit(); 
QWidget window;
QPushButton *button;

layout->addWidget(text);
button = new QPushButton();
button->setText(QChar(i+48));

QObject::connect(button,SIGNAL(clicked()),text,SLOT(setPlainText("hai")));

layout->addWidget(button);
window.setLayout(layout);
window.resize(500, 500);
window.show();

return app.exec();
}


You can't use connect like that. You cannot pass parameters to the SLOT that are not present in the connected SIGNAL.

You will need to connect the clicked() signal to your own slot (with no argument), and call the setPlainText function yourself (or emit a new signal that has a QString parameter).

The other option is to use a QSignalMapper, as described in the Signals and Slots advanced usage section.


I think that won't work, you cannot give a slot a default argument inside the connect statement. The SLOT macros actually just transforms its argument into a string and searches for the slots name in a list of registered slots for the text class.

You have to call your own slot that takes no arguments and calls setPlainText manually with the intended text. Perhaps Qt has some helper class in that direction, but your solution should not work.

By the way, have you actually tried this and got an error, or have you just posted it here without simply trying it out?


Your signal and slot are incompatible. Qt provides doc for this .

Try to visit this page .

In this it says , "The signals and slots mechanism is type safe: The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.) Since the signatures are compatible, the compiler can help us detect type mismatches. Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. "

Signal slot mechanism can be compared with (or boiled down to) function call. You are calling a function(slot) in a place where signal is emitted. Now imagine that the function expects some arguments and there is no default value. But you are trying to call the function. What will happen?. That's what happening in your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜