对于自定义Item窗口元素主要是为了体现出QT对于这方面的支持!就例如我们要自定义一个QListWidget中的ITEM我们要的不仅仅是一个Icon和一个QString我们需要的是更对对象的集合可以说我们要的是一个可以自定义的窗口,当然对于我们的菜单也是可以这样实现的,这篇文件就是本人的总结!最初的想法只是想让自己能够记住,毕竟人的记忆是有限的。废话不多说,其实都是一些我们现在还没有用到的函数,没有什么大不了的,只要了解了,相信你也知道怎么弄
这里讲的是菜单窗口,后面还会介绍其他的窗口
原理:
其实就是利用QWIdgetAction这个类来实现的,它有一个函数是SetDefaultWidget就可以搞定啦!
有图有真相:
这个蓝色的部分就是添加进去的窗口
直接上代码:
首先是构造函数中:
QMenuWidget::QMenuWidget(QWidget *parent) :
QMenu(parent)
{
this->setStyleSheet(
"QMenu{padding:5px;background:white;border:1px solid gray;}"
"QMenu::separator{height:1px;background:lightgray;margin:5px 0px 5px 0px;}"
"QMenu::item{padding:0px 40px 0px 30px;height:25px;}"
"QMenu::item:selected:enabled{background:lightgray;color:white;}"
"QMenu::item:selected:!enabled{background:transparent;}"
"QMenu::item:hover{background:lightblue;}"
);
creatAction(); //动作的初始化
creatWidgetAction();//自定义窗口的布局
translatorLanguage();//文本
addActions(); //添加动作
}
然后是接下来的代码:
void QMenuWidget::creatAction()
{
flash = new QAction(this);
quit = new QAction(this);
add = new QAction(this);
message = new QAction(this);
widgetAction = new QWidgetAction(this);
// flash->setIcon(QIcon());
// quit->setIcon(QIcon());
// add->setIcon(QIcon());
// message->setIcon(QIcon());
}
void QMenuWidget::creatWidgetAction()
{
textLabel = new QLabel();
textLabel->setText(tr("这是个窗口"));
messageLabel = new QLabel();
messageLabel->setText(tr("这是个窗口"));
actionWidget = new QWidget();
actionWidget->setStyleSheet("background:blue;color:white;");
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addWidget(textLabel);
mainLayout->addWidget(messageLabel);
actionWidget->setLayout(mainLayout);
widgetAction->setDefaultWidget(actionWidget);//这个就是最核心的地方啦!
}
void QMenuWidget::translatorLanguage()
{
flash->setText(tr("刷新"));
quit->setText(tr("退出"));
add->setText(tr("增加"));
message->setText(tr("更多信息"));
}
void QMenuWidget::addActions()
{
this->addAction(widgetAction);
this->addSeparator();
this->addAction(add);
this->addAction(flash);
this->addAction(message);
this->addSeparator();
this->addAction(quit);
}
ok,就是这样的。。。。
接下来会有其他的一些自定义窗口的文章,希望大家可以从中学到自己想要的知识!