Qt 按钮与选项卡关联实例(主要是qss使用)

话不多说,先上图吧:

基本上实现了这个功能,这个是书籍:

Qt5C++GUIProgrammingCookbook  书中的第二个小例子,我只是添加了一个点击按钮可以切换tabWidget的功能。

估计很多人会说,这不是一个非常简单的例子吗,没啥特别的,界面也不好看,反正你一定会吐槽的。

其实你多了解看看一下很多程序都是这个模式,比如:

 

      图中是不是很熟悉呀,点击一个按钮,达到不同的界面,实现界面的切换,只是这个例子没有贴好看的图,图贴的好,那就是焕然一新了 ,据这个例子呢,学习中多思考,就会有不同的感觉。

      好了先上布局:

布局非常的简单,大家估计很容易都能画出啦。接下来是对应的qss样式表:

QPushButton
{
	color: white;
	background-color: #27a9e3;
	border-width: 0px;
	border-radius: 3px;
}

QPushButton:hover
{
	color: white;
	background-color: #66c011;
	border-width: 0px;
	border-radius: 3px;
}

QPushButton:pressed
{
	color: white;
	background-color: yellow;
	border-width: 0px;
	border-radius: 3px;
}


QPushButton[pagematches=true]
{
	color: white;
	background-color: red;
	border-width: 0px;
	border-radius: 3px;
}

按钮4个状态的按钮,选中对应的为红色,然后不触发其他状态,让人觉得是选中的感觉;

那开始上代码部分吧:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_tabWidget_currentChanged(int index);

    void on_button1_clicked();

    void on_button2_clicked();

    void on_button3_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

对应的cpp文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStyle>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->button1->setProperty("pagematches", true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    // Set all buttons to false
    ui->button1->setProperty("pagematches", false);
    ui->button2->setProperty("pagematches", false);
    ui->button3->setProperty("pagematches", false);

    // Set one of the buttons to true
    if (index == 0)
        ui->button1->setProperty("pagematches", true);
    else if (index == 1)
        ui->button2->setProperty("pagematches", true);
    else
        ui->button3->setProperty("pagematches", true);

    // Update buttons style

      ui->button1->style()->polish(ui->button1);
      ui->button2->style()->polish(ui->button2);
      ui->button3->style()->polish(ui->button3);
}

void MainWindow::on_button1_clicked()
{
    ui->tabWidget->setCurrentIndex(0);
}

void MainWindow::on_button2_clicked()
{
    ui->tabWidget->setCurrentIndex(1);
}

void MainWindow::on_button3_clicked()
{
   ui->tabWidget->setCurrentIndex(2);
}

 是不是非常的简单:

      喜欢的朋友可以关注我的博客,你的点赞会让我更加有动力编写,谢谢,例子在后边的连接里,可以下载来看:

      链接:https://pan.baidu.com/s/1C0vRxnXMC29AcDLM9GK46A 
      提取码:csc9

如果连接失效的话,可以私信我,一起加油学习吧。

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值