开发者

Qt - widget - update

开发者 https://www.devze.com 2023-01-14 04:59 出处:网络
I am having a widget with a push button. I want, for every click on the push button one label should be addedin the widget. I am giving the code below, but is not working. I don\'t know why. Somebody

I am having a widget with a push button. I want, for every click on the push button one label should be added in the widget. I am giving the code below, but is not working. I don't know why. Somebody help me?

class EditThingsWindow:public QWi开发者_StackOverflow中文版dget
{
    Q_OBJECT

    QPushButton * add;

public:
    EditThingsWindow();

public slots:
    void addButtonClicked();
};

EditThingsWindow::EditThingsWindow():QWidget()
{
    QWidget* wid = this;
    wid->resize(400,400);

    add=new QPushButton(wid);
    add->setText("Add");
    add->move(20,10);
    line=new QLineEdit(wid);
    line->move(30,50);

    QObject::connect(add,SIGNAL(clicked()),this,SLOT(addButtonClicked()));
}

void EditThingsWindow::addButtonClicked()
{
    QLabel* label = new QLabel(this);
    label->move(200,160);
    label->setText(";;;;;;;;;;;;;;");
 }


A new QLabel is indeed added to the EditThingsWindow every time you click on the button. However, since the labels are not placed in a layout, and they are all moved at the same position with the same text (hence the same size), they all appear on top of each other, and you can only see the top one, which is probably why you think they are not being added.

Add a layout to the EditThingsWindow widget, and add each new QLabel to the layout, and you will see all the labels appear.


Just add layout and place your newborn labels into it.

 QHBoxLayout *layout = new QHBoxLayout; // or some another QLayout descendant
 layout->addWidget(newWidget);

 widget->setLayout(layout);

the only place I had to change is add layout into Widget and then

void EditThingsWindow::addButtonClicked() 
{
    QLabel * label=new QLabel(this);
    layout->addWidget(label);
    label->move(200,160);
    label->setText(";;;;;;;;;;;;;;");
}

got things done.

If you MUST (you don't!) mess with absolute positioning, you should do all these boilerplate code by yourself. Headers and includes omitted.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    EditThingsWindow w(0);
    w.show();
    return a.exec();
}

EditThingsWindow::EditThingsWindow(QWidget *parent):QWidget(parent)
{
i = 0;
setGeometry(2, 2, 400, 400);
add=new QPushButton(this);
add->setGeometry(2, 2, 100, 20);
add->setText("Add");
add->move(20,10);

QObject::connect(add,SIGNAL(clicked()),this,SLOT(addButtonClicked()));
}

void EditThingsWindow::addButtonClicked()
{
QLabel * label=new QLabel(this);
label->setGeometry(10, 30 + i* 30, 50, 20);
i++;
label->setText(";;;;;;;;;;;;;;");
label->show();
}
0

精彩评论

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