您现在的位置是:首页 > 技术文章网站首页技术文章
[Qt]QLabel点击事件
简述QT中 QLabel 可点击实现
效果:
Custom_control.h:
#include <QtWidgets> #include <QDesktopServices> #include <QUrl> class Custom_control : public QWidget { Q_OBJECT public: Custom_control(QWidget* parent = Q_NULLPTR); ~Custom_control(); protected: void InitUi(); private slots: bool eventFilter(QObject* obj, QEvent* event); //重写eventFilter(处理点击事件) private: QVBoxLayout* m_pThisLayout; //创建底部布局 QWidget* m_pThisWidget; //创建底部控件 QLabel* m_TestLabel04; //可点击标签 };
Custom_control.cpp:
#include "Custom_control.h" Custom_control::Custom_control(QWidget* parent) { InitUi(); } Custom_control::~Custom_control() { } void Custom_control::InitUi() { setMinimumSize(136, 154); setMaximumSize(500, 500); m_pThisLayout = new QVBoxLayout(this); //创建底部布局 //m_pThisLayout->setContentsMargins(0, 0, 0, 0); //设置左侧、顶部、右侧和底部边距 //m_pThisLayout->setSpacing(5); //设置各个控件之间的上下间距 //m_pThisLayout->setMargin(0); //设置控件与窗体左右边距 //m_pThisLayout->addStretch(0); //增加伸缩量 m_pThisWidget = new QWidget(this); //创建底部控件 m_pThisWidget->setContentsMargins(0, 0, 0, 0); //设置上下左右间距 m_pThisWidget->setStyleSheet("background-color: white"); m_pThisLayout->addWidget(m_pThisWidget); //添加底部控件到布局 m_TestLabel04 = new QLabel(m_pThisWidget); //添加Qlabel标签 m_TestLabel04->setText("Test04"); //设置文本 m_TestLabel04->installEventFilter(this); //注册安装事件过滤 connect(m_TestLabel04, SIGNAL(clicked()), this, SLOT(eventFilter())); //连接信号与槽 m_pThisLayout->addWidget(m_TestLabel04, 0, Qt::AlignHCenter); //添加Qlabel进布局,并居中 m_pThisLayout->addStretch(1); //添加拉伸 } bool Custom_control::eventFilter(QObject* obj, QEvent* event) //处理点击事件 { if (qobject_cast<QLabel*>(obj) == m_TestLabel04 && event->type() == QEvent::MouseButtonRelease) { const QUrl regUrl(QLatin1String("http://www.hack1412.com")); //打开网址 QDesktopServices::openUrl(regUrl); // QMessageBox::information(this, "提示", QString("点击了该Label")); //提示窗口 return true; } return false; }
上一篇:[Vs]项目中可以使用的路径宏
下一篇:[Qt]切换皮肤样式
相关文章
文章评论 (0)