由于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来切换小部件,在我的应用程序中,小部件要复杂得多,我不能每次想要交换时都重新创建它们。
我认为从性能的角度来看,每次你想要切换帧时删除和重新创建层是不好的做法,将两帧都添加到层中,然后只设置你想要出现的帧可见会更容易。此外,布尔isRed也不是必需的,因为关于可见性的信息包含在每帧本身中…
试试这个:
QFrame *red = NULL;
QFrame *blue = NULL;
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
red = new QFrame(this);
red->setFixedSize(100,100);
red->setStyleSheet("background-color:red");
red->setHidden(false);
blue = new QFrame(this);
blue->setFixedSize(100,100);
blue->setStyleSheet("background-color:blue");
blue->setHidden(true);
layout->addWidget(red);
layout->addWidget(blue);
this->setLayout(layout);
}
void Widget::mouseReleaseEvent(QMouseEvent *){
printf("clicked.n");
fflush(0);
red->setHidden(!red->isHidden());
blue->setHidden(!blue->isHidden());
}
布局会破坏它的子布局。因为addWidget
占有所有权,所以delete layout
也会删除红色和蓝色的小部件