由于 mouseEvent,我希望红色和蓝色小部件在每次点击时切换位置。相反,红色切换到蓝色,然后它永远不会切换回来,为什么?
Frame *red = NULL;
Frame *blue = NULL;
bool isRed = true;
Frame::Frame(QWidget *parent) :
QFrame(parent)
{
}
Frame::~Frame(){
printf("deleted.\n");
fflush(0);
}
void QLayout_clear(QLayout* layout, bool deleteWidgets){
QLayoutItem* item;
QLayout* childLayout;
while ((item = layout->takeAt(0)) != NULL){
QWidget* widget = item->widget();
if (widget != NULL){
layout->removeWidget(widget);
if (deleteWidgets){
delete widget;
}
} else if (childLayout = item->layout()){
QLayout_clear(childLayout, deleteWidgets);
}
//delete item;
}
}
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout;
this->setLayout(layout);
red = new Frame;
red->setFixedSize(100,100);
red->setStyleSheet("background-color:red");
blue = new Frame;
blue->setFixedSize(100,100);
blue->setStyleSheet("background-color:blue");
layout->addWidget(red);
}
void Widget::mouseReleaseEvent(QMouseEvent *){
printf("clicked.\n");
fflush(0);
QVBoxLayout *layout = (QVBoxLayout *)this->layout();
if (1){ //it doesnt matter if this is 1 or 0
delete layout;
layout = new QVBoxLayout;
this->setLayout(layout);
} else {
QLayout_clear(layout, false);
}
if (isRed){
layout->addWidget(blue);
isRed = false;
} else {
layout->addWidget(red);
isRed = true;
}
}
注意:这里我使用一个简单的 QFrame 来切换小部件,在我的应用程序中,小部件要复杂得多,每次我想交换时我都无法重新创建它们。