日期:2014-05-16  浏览次数:20717 次

QT中如何让一个按钮单击后更新一个TextEdit
我的程序如下,想让BUTTON CLICKED后让pTextEdit2显示pTextEdit1的内容,不知道哪里做错了 
才用QT,不是很了解,希望大家帮忙看看 


C/C++ code


#include <QT/QApplication.h>
#include <QT/QPushButton.h>
#include <QT/QTextEdit.h>

#include <string>

class MyWidget : public QWidget
{
private:
    QTextEdit *pText1,*pText2;
    QPushButton *pButton;
public:
    MyWidget(QWidget* parent);
    ~MyWidget();
public slots:
    void buttonPressed();
};

MyWidget::MyWidget(QWidget* parent)
:QWidget(parent)
{
    setFixedSize(300,300);
    
    pText1 = new QTextEdit("Edit1",this);
    pText2 = new QTextEdit("Edit2",this);
    pButton = new QPushButton("Button",this);
    
    pText1->resize(100,100);
    pText1->setGeometry(0,0,100,100);
    
    pText2->resize(100,100);
    pText2->setGeometry(120,0,100,100);
    
    pButton->resize(100,30);
    pButton->setGeometry(10,200,100,30);
    
    QObject::connect(pButton,SIGNAL(clicked()),this,SLOT(buttonPressed()));
}

MyWidget::~MyWidget()
{
    delete pText1;
    delete pText2;
    delete pButton;
}

void MyWidget::buttonPressed()
{
    pText2->setText(pText1->toPlainText());
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    
    QWidget window;    
    window.resize(400,400);

    MyWidget my_widget(&window);
    my_widget.setGeometry(10,10,300,300);

    window.show();
    return app.exec();
}






------解决方案--------------------
确实是刚接触QT
QT 对自定义SLOT 是有要求的
1 在类中引用 Q_OBJECT 宏
2 类声名要单独放到一个.H 文件中去

我将你的代码改动后,成功执行!

另注:QT3和QT4有很多不同,建议使用比较新一写的版本.