Men的博客

欢迎光临!

0%

QT常用技巧

tableView mvc模型

QAbstractItemDelegate
QAbstractItemModel
QAbstractItemView

获取屏幕分辨率

qDebug()<< “screen width:”<QApplication::desktop()-width();
qDebug()<< “screen height:”<QApplication::desktop()-height();

获取客户使用区大小

qDebug()<< “screen avaliabe width:”<QApplication::desktop()-availableGeometry().width();
qDebug()<< “screen avaliabe heigth:”<QApplication::desktop()-availableGeometry().height();

获取应用程序矩形大小

qDebug()<< “application avaliabe width:”<QApplication::desktop()-screenGeometry().width();
qDebug()<< “application avaliabe heigth:”<QApplication::desktop()-screenGeometry().height();

设置 icon

QIcon icon;
icon.addPixmap(QPixmap(QString::fromUtf8(“:/bmp/logo.png”)), QIcon::Normal, QIcon::Off);
WndTest->setWindowIcon(icon);
WndTest->setIconSize(QSize(256, 256));

字体更改

QFont font;
font.setPointSize(40);
font.setBold(true);
font.setWeight(75);
QLabel *lfontnew = new QLabel();
lfontnew->setFont(font);

文本颜色更改

void WndTest::changeColor( QWidget *obj, QColor clr )
{
QPalette *palette = new QPalette();
palette->setColor(QPalette::Text,clr);
obj->setPalette(*palette);
delete palette;
}

取消pushbutton点击时出现的边框效果

btn->setFocusPolicy(Qt::NoFocus);

把所有按钮添加一个buttongroup

然后选中所有按钮,在右下角属性中将checkable打勾,然后在代码中通过ui->buttonGroup->setExclusive(true);设置该组按钮为互斥

设置图像可自适应标签大小:

QLabel::setScaledContents(true);
用label显示图片时,图片有可能会把label撑大,这时只要给label一个最小值,无论图片有多大,label都不会再被撑大了

QMap来保存所创建的label对象

动态添加一系列label时,可用QMap来保存所创建的label对象,如:graphicsMap[number] = label;

获取控件的全局坐标:

int x = label->mapToGlobal(QPoint(0, 0)).x();
int y = label->mapToGlobal(QPoint(0, 0)).y();
int w = label->geometry().width();
int h = label->geometry().height();

设置有背景的控件

比如QTabWidget,让其背景透明可设置样式表时加上 background-color:argb(0,0,0,0); 原来自带的背景就透明掉了;

在主程序外调用qApp

可以使用宏定义获得QApplication的指针
#define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
或者
#define qApp QCoreApplication::instance()
11、当调用QComboBox::clear()时,index会变为-1而不是0,同时会触发currentIndexChange()这个槽函数。

信号常用触发形式

clicked——QPushbutton
triggered——QAction
toggled ——QRadioButton(单选按钮)

append函数可以实现自动换行显示。

delay函数用处

:当现实文字信息换行时,会等到整个槽函数执行完成之后才将全部信息打印出来;这是在中间插一句delay();打断一下即可正常显示。

槽函数

connect(button,SIGNAL(clicked()),this,SLOT(槽函数)));
//connect(对象,发出的信号,对象,处理信号的槽函数);
connect(&b1,&QPushButton::clicked,this,&MyWidget::close);
槽函数的特性:

(1)槽函数没有返回值;

(2)槽函数需要与信号函数对应;

(3)槽函数的参数 是为了接收信号传过来的数据;

(4)参函数的参数应该是不大于信号参数的个数,可以少于;

(5)槽函数可以重载;

发送信号

emit sigSub();

布局方式

QBoxLayout可以在水平方向或垂直方向上排列控件。
QHBoxLayout:水平布局,在水平方向上排列控件。
QVBoxLayout:垂直布局,在垂直方向上排列控件。

QTextEdit

QTextDocument *doc=showWidget->text->document();
doc->print(&printer);

图形方法

QPainterPath path;
Path.moveTo(0,0);
path.lineTo(200,0);
path.lineTo(200,100);
path.lineTo(0,100);

QPushButton

QPushButton* btn = new QPushButton;
// btn->show(); // 用顶层方式弹出。若想在MyWiget窗口中显示,就需要依赖MyWidget窗口
// 设置父亲
btn->setParent(this);
// 设置文字
btn->setText(“Nemo”);// 将char隐式类型转化为QString
// 重置按钮大小
btn->resize(150 ,100);
// 创建按钮第二种方式
QPushButton
btn2 = new QPushButton(“第二按钮”, this); //此方式可以安装btn2大小进行显示
// 重置窗口大小
this->resize(400, 200);// 宽 高
// 后创建,显示靠前
// 移动第二个按钮
btn2->move(100, 100);
// 重置窗口标题
setWindowTitle(“xxx—xxx”);
// 设置窗口大小
setFixedSize(800, 600)

模态对话框

dlg.exec();//阻塞

非模态对话框

dlg.setAttribute(Qt::WA_DeleteOnClose);
dlg->show();

提示对话框

#include
QMessageBox::about(this,”Tips”,”hello”);
if(QMessageBox::Ok == QMessageBox::question(this,”Tips”,”hello”,QMessageBox::Ok|QMessageBox::Cancel))
{

停靠窗口

QDockWidget *dockWidget = new QDockWidget(tr(“Dock Widget”), this);
dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
addDockWidget(Qt::LeftDockWidgetArea, dockWidget);

动态修改CentralWidget

centralWidget()->setParent(0);
//新的CentralWidget
setCentralWidget(_newCentral);

分裂器

QSplitter *splitter= new QSplitter;
splitter->addWidget(t_widget);
splitter->addWidget(p_widget);
splitter->setStretchFactor(1,3);
splitter->show();

QListWidget,与QListView区别

QListWidget是基于Item,而QListView是基于Model的

Widget 控件(组件)在创建时是不可见的,它可以包含子控件,在删除该 Widget 时,子控件也将一
起删除。
#include // 时钟效果数字
#include //调试类
#include //标准输入框
#include //
#include
#include
#include //表格组件:内置了网络布局
#include
#include //列表组件:
#include
#include //树形组件:
#include
#include
#include //表项
#include
#include
#include //鼠标事件
#include //按键事件

组件

QAbstractButton类

1.是按钮部件的抽象基类,提供了按钮所共有的功能。
2.实现了一个抽象按钮,并且让它的子类来指定如何处理用户的动作,并指定如何绘制按钮。
3.提供了点击和勾选按钮。    

QRadioButton和QCheckBox类只提供了勾选按钮,
QPushButton和QToolButton提供了点击按钮,如果需要的话,它们还可以提供切换行为。
任何按钮,都可以显示一个包含文本和图标的标签。setText()用来设置文本,setIcon()可以置图标。如果按钮被禁用,其标签更改为“disabled”样式。

常用状态:
isDown() 按钮是否被按下。
isChecked() 按钮是否被选中。只有切换按钮才能被切换为选中或不选中(请看下面)。
isEnabled() 按钮是否可以被用户按下。
setAutoRepeat() 如果用户按下按钮,按钮是否可以自动回复。
setToggleButton() 按钮是否是一个切换按钮。

信号:QAbstractButton提供了四个信号:
pressed() 当鼠标光标在按钮内,鼠标左键被按下时,发送此信号。
released() 当鼠标左键被释放时,发送此信号。
clicked() 当按钮被按下然后又被释放,或按下快捷键,或当animateClick()被调用时,发送此信号。
toggled() 当切换按钮的状态变化时,发送此信号。
使用:
QAbstractButton *pButton = new QPushButton(this);
// 设置图标、图标大小、文本
pButton->setIcon(QIcon(“:/Images/logo”));
pButton->setIconSize(QSize(18, 18));
pButton->setText(“Click Me”);
// 连接信号与槽
connect(pButton, &QAbstractButton::clicked, this, &MainWindow::onClicked);
void MainWindow::onClicked()
{
qDebug() << “Enter…”; //点击按钮时,就会输出信息”Enter…”。
}
互斥:只能选中一个按钮
raidobutton_1->setCheckable(true); //设置可选
raidobutton_1->setChecked(true); //设置选中

//QPushButton //命令按钮
QPushButton *file_button = new QPushButton(“文 件”);

QtoolButton //工具按钮 //ToolButton 控件

QToolButton类提供了用于命令或选项可以快速访问的按钮,通常可以用在QToolBar里面。
工具按钮和普通的命令按钮不同,通常不显示文本,而显示图标。

RadioButton 单选按钮,切换按钮

QRadioButton部件提供了一个带有文本标签的单选框(单选按钮)。
可以切换选中(checked)或未选中(unchecked)状态的选项按钮
raidobutton_1 = new QRadioButton(“男”);
raidobutton_1->setCheckable(true); //可选
raidobutton_1->setChecked(true); //选中
raidobutton_2 = new QRadioButton(“女”);
raidobutton_2->setCheckable(true);

按钮组QButtonGroup //单选按钮做互斥

如果你需要为属于同一父部件的单选框设置多个互斥按钮组,把它们加入QButtonGroup中。
QButtonGroup *button_group = new QButtonGroup;
button_group->addButton(raidobutton_1);

button_group->addButton(raidobutton_2);

//QCheckBox //复选框,选项按钮,可多选
like_box_1 = new QCheckBox(“足 球”);
like_box_1->setCheckable(true);
like_box_1->setChecked(true);
like_box_2 = new QCheckBox(“蓝 球”);
like_box_2->setCheckable(true);

QSpinBox和QDoubleSpinBox均派生自QAbstractSpinBox
QSpinBox旨在处理整数和离散值(例如:月份名称)
QDoubleSpinBox则用于处理浮点值。默认的精度是2位小数,但可以通过setDecimals()来改变。
他们之间的区别就是处理数据的类型不同,其他功能都基本相同。

QSpinBox做年龄

QSpinBox *age_box;
age_box = new QSpinBox;
age_box->setRange(1,300);        // 范围
age_box->setSingleStep(1);        // 步长
age_box->setValue(24);            // 当前值(默认值)

QDoubleSpinBox

上面的所有功能对于QDoubleSpinBox同样适用。
主要使用setDecimals()设置精度,然后利用setSingleStep()来设置步长即可。
QDoubleSpinBox *pSpinBox = new QDoubleSpinBox(this);
pSpinBox->setRange(0, 20); // 范围
pSpinBox->setDecimals(3); // 精度
pSpinBox->setSingleStep(0.005); // 步长

QToolBox类: 提供了一个列(选项卡式的)部件条目

可以在一个tab列上显示另外一个,并且当前的item显示在当前的tab下面。
每个tab都在tab列中有一个索引位置。tab的item是一个QWidget 。 
 1.创建QGroupBox,并设置布局管理器为竖直布局
QGroupBox *group_1 = new QGroupBox;
QVBoxLayout *vlayout_1 = new QVBoxLayout(group_1);   
  2.创建QToolButton,将把按钮加入竖直布局
QToolButton *button_1_1 = this->add_button("贝 贝","://images/bb.png");
QToolButton *button_1_2 = this->add_button("京 京","://images/jj.png");
QToolButton *button_1_3 = this->add_button("欢 欢","://images/hh.png");

//封装,添加用户函数
QToolButton *MyQQ::add_button(const QString &name,const QString &path) //添加一个用户
{
QToolButton *toolbutton_1_1 = new QToolButton;
toolbutton_1_1->setText(name); //设置按钮文本
toolbutton_1_1->setIcon(QIcon(path)); //设置按钮图片
toolbutton_1_1->setIconSize(QSize(ICONWIDTH,ICONHEIGHT)); //设置按钮大小
toolbutton_1_1->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //设置图片和文本的样式
toolbutton_1_1->setAutoRaise(true); //设置自动弹出
this->connect(toolbutton_1_1,SIGNAL(clicked(bool)),this,SLOT(slot_message()));
return toolbutton_1_1;
}

QFrame

Frame 控件(框架)用来存放其他控件,也可用于装饰。它一般用来作为更加复杂容器的基础,也可
以用在 form 中作为占位控件。

QLineEdit

1.允许用户输入和编辑单行纯文本,提供了很多有用的编辑功能,包括:撤消和重做、剪切和粘贴、拖放
2.通过改变输入框的echoMode(),同时也可以设置为一个“只写”字段,用于输入密码等。
3.文本的长度可以被限制为maxLength(),可以使用一个validator()或inputMask()来任意限制文本

 QLineEdit *lineEdit;                                //声明 QLineEdit 控件
lineEdit = new QLineEdit(this);                    //创建 QLineEdit 控件
lineEdit->setGeometry(QRect(100,100,200,25));    //位置大小

QTextEdit:

//文本域,多行文本框
可以使用setText()或insert()来改变文本,通过text()来获取文本;
QTextEdit *textEdit; //声明
textEdit = new QTextEdit(this); //实例 QTextEdit 控件
textEdit->setGeometry(QRect(50,50,200,150)); //控件位置大小
textEdit->setText(“我是第一行
我是第二行”); //内容

QComboBox

#include //下拉列表
QComboBox *comboBox; //声明
comboBox = new QComboBox(this); //构造控件
//edu_box->addItem(“高 中”);
comboBox->setGeometry(QRect(50,50,120,25)); //控件显示位置大
QStringList str;
str << “数学” << “语文” << “地理”; //定义字符串列表
comboBox->addItems(str); //将字符串列表绑定 QComboBox 控件

QSpinBox

#include //整形分量框
QSpinBox *spinBox; //声明控件
spinBox = new QSpinBox(this); //创建
spinBox->setGeometry(QRect(50,50,100,25)); //位置
spinBox->setRange(0,200); //值范围
spinBox->setValue(10); //初始值
spinBox->setSuffix(“元”); //后缀
spinBox->setPrefix(“$”); //前缀

QFileDialog

//标准文件对话框:获取文件名
#include
QLineEdit *fileedit; //声明文件对话框
fileedit = new QLineEdit; //构建对话框
//构造按钮
//连接槽函数
this->connect(file_button,SIGNAL(clicked(bool)),this,SLOT(slot_getFile()));
void DialogGui::slot_getFile()//获取文件名的槽函数
{
qDebug() << __func__ << endl; //Qt中输出要用调试输出
//打开文件对话框,获取文件路径,修改lineedit的内容
QString path = QFileDialog::getOpenFileName(this,”文件对话框”,”D:\“,”C++头文件(*.h);;C++源文件(*.cpp);;所有文件(*.*)”); //打开文件对话框
if(!path.trimmed().isEmpty()) //判断用户是否点击打开,trimmed()去除首尾空格
fileedit->setText(path); //通过文本的设置函数,将获得的文本地址赋给框
}

QFontDialog

//字体对话框:设置字体
#include
QLineEdit *fontedit; //声明对话框
fontedit = new QLineEdit(“中国,加油”); //构建对话框,并初始化
//构造按钮 。。。
//连接槽函数
this->connect(font_button,SIGNAL(clicked(bool)),this,SLOT(slot_getFont()));
void DialogGui::slot_getFont()
{
qDebug() << __func__ << endl; //Qt中输出要用调试输出
bool isok = false; //打开字体对话框
QFont font = QFontDialog::getFont(&isok,QFont(“隶书”,35),this,”字体对话框”);
if(isok) //如果为true表示用户点击了确定
fontedit->setFont(font); //通过字体的设置函数,将获得的字体赋给框
}

QColorDialog

//颜色对话框:颜色填充
#include
QFrame *colorFrame; //声明颜色的方框
colorFrame = new QFrame; //构造方框
colorFrame->setFrameShape(QFrame::Box); //设置方框的形状
colorFrame->setAutoFillBackground(true); //设置方框的背景颜色自动填充
//构造按钮 。。。
//连接槽函数
this->connect(color_button,SIGNAL(clicked(bool)),this,SLOT(slot_getColor()));
void DialogGui::slot_getColor() //获取颜色
{
qDebug() << __func__ << endl; //Qt中输出要用调试输出
QColor color = QColorDialog::getColor(Qt::red,this,”颜色对话框”);
if(color.isValid()) //验证颜色数是否有效
{
//设置颜色:通过Palette去设置颜色
colorFrame->setPalette(QPalette(color));//通过颜色的设置函数,将获得的颜色赋给框
}
}

QInputDialog

//标准输入框:手动输入,如输入名字,年龄等信息;
#include
name_label = new QLabel; //构造一个文本框
name_label->setAlignment(Qt::AlignCenter); //设置label上的文本居中
name_label->setFrameStyle(QFrame::Panel | QFrame::Sunken); //设置label的样式为panel和sunken
QPushButton *name_button = new QPushButton; //构造一个按钮
name_button->setIcon(QIcon(“://images/btn.png”));//给按钮做一个图片
//连接槽函数
this->connect(name_button,SIGNAL(clicked(bool)),this,SLOT(slot_getName()));

void InputDialogGui::slot_getName() //设置槽函数实现功能
{
//打开文本输入框,获取得文本,设置到label中
bool ok = false;
QString name = QInputDialog::getText(this,”文本输入框”,”请输入姓名:”,QLineEdit::Normal,”张 三”,&ok);
if(ok && !name.trimmed().isEmpty()) //如果 用户点击了确定
name_label->setText(name); //通过框的设置函数,将获得的名字赋给框
}
//下面三个分别实现
//年龄(选项输入框getItem),性别(整型输入框getInt),身高(浮点型输入框getDouble)
void InputDialogGui::slot_getSex() //1.年龄(选项输入框getItem)
{
QStringList sexlist;
sexlist.push_back(“男”);
sexlist.push_back(“女”);
sexlist.push_back(“人妖”);
bool ok = false;
QString sex = QInputDialog::getItem(this,”选项输入框”,”请选择性别:”,sexlist,1,false,&ok);
if(ok)
sex_label->setText(sex);
}
void InputDialogGui::slot_getAge() //2.性别(整型输入框getInt)
{
bool ok = false;
int age = QInputDialog::getInt(this,”整型输入框”,”请输入年龄:”,24,1,300,2,&ok);
if(ok)
age_label->setText(QString::number(age));
}
void InputDialogGui::slot_getHeight() //3.身高(浮点型输入框getDouble)
{
bool ok = false;
qreal height = QInputDialog::getDouble(this,”浮点型输入框:”,”请输入身高:”,150,1,300,1,&ok);
if(ok)
height_label->setText(QString::number(height));
}

QMessageBox

#include //标准消息对话框
QPushButton *question_button = new QPushButton(tr(“question”));
this->connect(question_button,SIGNAL(clicked(bool)),this,SLOT(slot_question()));
void MessageBoxGui::slot_question()
{
int button = QMessageBox::question(this,tr(“question message box”),tr(“are you close file?”),QMessageBox::Ok | QMessageBox::Cancel);
if(button == QMessageBox::Ok) //表示用户点击了OK按钮
messlabel->setText(tr(“question/ok”)); //在实际使用中,应该实现实际功能
else if(button == QMessageBox::Cancel) //表示用户点击了cancel按钮
messlabel->setText(tr(“question/cancel”));
} //以上未系统的消息对话框

//自定义的消息对话框
QPushButton *constom_button = new QPushButton(tr(“constom”));
this->connect(constom_button,SIGNAL(clicked(bool)),this,SLOT(slot_comstum()));
void MessageBoxGui::slot_comstum() //利用槽函数自定义消息对话框
{
//1.创建消息对话框对象
QMessageBox constom_mbox;
//2.设置对话框的属性
constom_mbox.setWindowTitle(tr(“comstum message box”));
constom_mbox.setIconPixmap(QPixmap(“://images/linuxredhat.png”));
constom_mbox.setText(tr(“this is my comstum message box”));
//3.添加按钮
QPushButton *lock_button = constom_mbox.addButton(tr(“lock”),QMessageBox::ActionRole);
QPushButton *unlock_button = constom_mbox.addButton(tr(“unlock”),QMessageBox::ActionRole);
QPushButton *cancel_button = constom_mbox.addButton(QMessageBox::Cancel);
//4.运行
// constom_mbox.show(); //error,无法判断用户点击的按钮
constom_mbox.exec(); //对于dialog及子类的显示必须调用exec();
//5.获取用户点击的按钮,判断
QAbstractButton *button = constom_mbox.clickedButton(); //获取用户点击的按钮,
if(button == lock_button)
messlabel->setText(tr(“constum/lock”));
else if(button == unlock_button)
messlabel->setText(tr(“constum/unlock”));
else if(button == cancel_button)
messlabel->setText(tr(“constum/cancel”));
}

QDateTimeEdit

#include //日期时间编辑器
提供了一个部件,用于编辑日期和时间。
通过使用键盘或箭头键来增加和减少日期和时间值。
日期和时间的格式按照setDisplayFormat()设置的显示。

// 设置日期时间格式
QDateTimeEdit *dateTimeEdit = new QDateTimeEdit(this);
QDateTimeEdit *dateTimeEdit2 = new QDateTimeEdit(QDateTime::currentDateTime(), this);
QDateTimeEdit *dateEdit = new QDateTimeEdit(QDate::currentDate(), this);
QDateTimeEdit *timeEdit = new QDateTimeEdit(QTime::currentTime(), this);
dateTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
dateTimeEdit2->setDisplayFormat("yyyy/MM/dd HH-mm-ss");
dateEdit->setDisplayFormat("yyyy.M.d");
timeEdit->setDisplayFormat("H:mm");
yyyy:年,4个数表示。 
MM:月,01-12。 
dd:日,01-31。 
HH:时,00-23。 
mm:分,00 - 59。 
ss:秒,00-59。

    

QDateEdit和QTimeEdit均继承自QDateTimeEdit,许多特性和功能都有QDateTimeEdit提供。
不要用QDateEdit来设置或获取时间,也不要用QTimeEdit来设置或获取日期。如果要同时操作日期时间,请使用QDateTimeEdit。
//dateEdit->setDisplayFormat(“yyyy/MM/dd”);
//timeEdit->setDisplayFormat(“HH:mm:ss”);

QTimeEdit

//时间编辑器
#include
time:保存了部件的显示时间。
minimumTime:定义了用户可以设置的最小时间。
maximumTime:定义了用户可以设置的最大时间。
displayFormat:包含了一个字符串用于格式化时间
QTimeEdit *timeEdit = new QTimeEdit(QTime::currentTime(), this);

QDateEdit

//日期控件
#include
date:保存了部件的显示日期。
minimumDate:定义了用户可以设置的最小日期。
maximumDate:定义了用户可以设置的最大日期。
displayFormat:包含了一个字符串用于格式化日期。
QDateEdit *dateEdit = new QDateEdit(QDate::currentDate(), this);

QDateTime

//日期时间
#include
QDateTime dateTime = dateEdit->dateTime();

QDate

//日期类
#include
QDate date = dateEdit->date();

QTime

//时间类
#include
QTimeEdit *timeEdit; //声明
timeEdit = new QTimeEdit(this); //构造控件
timeEdit->setGeometry(QRect(50,50,120,25)); //位置
QDateTime sysTime = QDateTime::currentDateTime();//获取系统时间
//获取时分秒以“:”号拆分赋予 list 数组
QStringList list = sysTime.toString(“hh:mm:ss”).split(‘:’);
//将时分秒绑定控件 timeEdit- >setTime(QTime(list[0].toInt(),list[1].toInt(),list[2].toInt()));

bdate_edit_1->setDate(bdate);                    //设置日期
bdate_edit_1->setDisplayFormat("yyyy年M月dd日");   //设置日期显示格式
bdate_edit_1->setCalendarPopup(true);               //弹出日历

//1.获取时间并转化为字符串
QTime time = QTime::currentTime();
QString tim_str = time.toString("hh:mm");
//2.根据isshow控制符来决定是否显示:
if(isshow)
    tim_str[2] = ':';
else
    tim_str[2] = ' ';
//3.显示时间字符串
this->display(tim_str);

QTimer

//实时更新时间
#include
QTimer *timer; //声明
timer = new QTimer;
connect(timer,SIGNAL(timeout()),this,SLOT(timerTime()));

void MainWindow::timerTime(){
QDateTime sysTime = QDateTime::currentDateTime();//获取系统时间
label->setText(sysTime.toString());
}
    

布局:

//网格布局
QGridLayout:把子窗口排列在一个二维的网格中,窗口可占据多个单元格。
     QGridLayout *left_layout = new QGridLayout;
    left_layout->addWidget(lable_1,0,0);        //lable_1   nameedit
    left_layout->addWidget(nameedit,0,1);        //lable_2    sex_hlayout
    left_layout->addWidget(lable_2,1,0);
    left_layout->addLayout(sex_hlayout,1,1);
   
//竖直布局        
QVBoxLayout:把子窗口从上到下排列在一个垂直列上。
    QVBoxLayout *right_layout = new QVBoxLayout;
    right_layout->addLayout(head_layout);
    right_layout->addWidget(label_10);
    right_layout->addWidget(indiv_edit);

//水平布局
QHBoxLayout:把子窗口从左到右排列在一个水平行上。
    sex_hlayout->addWidget(raidobutton_1);
    sex_hlayout->addWidget(raidobutton_2);
    sex_hlayout->addStretch();    //添加了一个伸缩空间
    //在第一个控件之前添加伸缩,这样所有的控件就会居右显示。
    //在最后一个控件之后添加伸缩,这样所有的控件就会居左显示。
    //在第一个控件之前、最后一个控件之后添加伸缩,这样所有的控件就会居中显示。
    //在每一个控件之间都添加伸缩,这样所有的控件之间的间距都会相同。

//表单布局
QFormLayout:管理输入型控件和关联的标签组成的那些Form表单。
    把子窗口按照标签-输入框的形式排列在两列。    
    两列和若干行组成的形式时,QFormLayout更为方便些
    多行多列,应毫不犹豫的尽量使用栅格布局QGridLayout
    QFormLayout *pLayout = new QFormLayout();
    pLayout->addRow(QStringLiteral("用户名:"), pUserLineEdit);
    pLayout->addRow(QStringLiteral("密码:"), pPasswordLineEdit);
    pLayout->addRow(QStringLiteral("验证码:"), pVerifyLineEdit);
    pLayout->setSpacing(10);
    pLayout->setMargin(10);
    setLayout(pLayout);
通过addRow()来创建一个带有给定文本的QLabel及QWidget控件行,它们可以自动的设置为伙伴关系。

//控制表单行的显示策略
QFormLayout::RowWrapPolicy枚举:
    QFormLayout::DontWrapRows    0    输入框始终在标签旁边
    QFormLayout::WrapLongRows 1    标签有足够空间适应,最小大小比可用空间大,输入框会被换到下一行
    QFormLayout::WrapAllRows    2    输入框始终在标签下边
    
//窗体布局    
QstackLayout    

间隔器:
    水平间隔器:Horizontal Spacer
    竖直间隔器:Vertical Spacer   
    
    

QTableWidget

    在单元格中添加控件:
    QComboBox *comBox = new QComboBox();
    comBox->addItem("F");
    comBox->addItem("M");
    ui->qtablewidget->setCellWidget(0,3,comBox);//这里不是setItem而是setCellWidget
    为单元格添加checkBox:

    QTableWidgetItem *item = new QTableWidgetItem();
    //设置item的check状态的时候,item会自动变成QCheckBox的样子,
    //不必通过setCellWidget专门插入QCheckBox控件
    //通过item->checkState()可以获取该item是否勾选
    item->setCheckState(Qt::Unchecked);
    ui->tableWidgetCourseList->setItem(rowIndex, columnIndex, item);
    单元格中显示字符串:
    QTableWidgetItem *item = new QTableWidgetItem(QString("xx"));
    ui->tableWidgetCourseList->setItem(rowIndex, columnIndex, item);
    设置单元格关联的自定义数据:
    QTableWidgetItem *item = new QTableWidgetItem(QString(""));
    QVariant courseModelVariant=QVariant::fromValue(MyClass("xx"));
    item->setData(USER_DEFINE_ROLE,courseModelVariant);
    this->ui->tableWidgetCourseList->setItem(rowIndex, columnIndex, item);
    获取单元格关联的自定义数据:
    QTableWidgetItem * item = this->ui->tableWidgetCourseList->item(row,col);
    Myclass model = item->data(USER_DEFINE_ROLE).value<MyClass>();
    设置单元格中的文本对齐方式:
    ui->tableWidgetCourseList->item(rowIndex, columnIndex)->setTextAlignment(Qt::AlignCenter);
    通过x,y坐标获取所在的item对象:
    QModelIndex index = ui->tableWidgetCourseList->indexAt(QPoint(x,y));
    int row = index.row();
    int col = index.column();
    QTableWidgetItem * item = ui->tableWidgetCourseList->item(row,col);
    设置表头的列宽:
    ui->tableWidgetCourseList->horizontalHeader()->resizeSection(colIndex,20);//宽20
    设置列宽自适应:
    ui->tableWidgetCourseList->horizontalHeader()->setSectionResizeMode(colIndex,QHeaderView::Stretch);
    初始化表头文本:
    QStringList headerText;
    headerText.append("列1");
    headerText.append("列2");
    headerText.append("列3");
    ui->tableWidgetCourseList->setHorizontalHeaderLabels(headerText);
    为表头添加复选框按钮:

    在表头上添加复选框不能通过在表头单元格中添加QCheckBox的方式实现,必须进行重绘,下面的代码是我们自定义的表头类
    myqheaderview.h的内容:
    //该类实现自定义的表头,主要是为了在表头中加入CheckBox控件
    class MyQHeaderView : public QHeaderView
    {
        Q_OBJECT
    public:
        explicit MyQHeaderView(Qt::Orientation orientation, QWidget *parent = 0);
     
        void setChecked(bool checked);
     
    signals:
        void headCheckBoxToggled(bool checked);
     
    protected:
        void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
        void mousePressEvent(QMouseEvent *event);
     
    private:
        QRect checkBoxRect(const QRect &sourceRect) const;
     
        bool m_isOn;
    };
    myqheadview.cpp的内容:

    MyQHeaderView::MyQHeaderView(Qt::Orientation orientation, QWidget *parent)
        : QHeaderView(orientation, parent)
        , m_isOn(false)
    {
        // set clickable by default
        setChecked(false);
    }
     
    void MyQHeaderView::setChecked(bool checked)
    {
        if (isEnabled() && m_isOn != checked)
        {
            m_isOn = checked;
            updateSection(0);
            emit headCheckBoxToggled(m_isOn);
        }
    }
     
    void MyQHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
    {
        painter->save();
        QHeaderView::paintSection(painter, rect, logicalIndex);
        painter->restore();
        if (logicalIndex == 0)
        {
            QStyleOptionButton option;
            if (isEnabled())
                option.state |= QStyle::State_Enabled;
            option.rect = checkBoxRect(rect);
            if (m_isOn)
                option.state |= QStyle::State_On;
            else
                option.state |= QStyle::State_Off;
            style()->drawControl(QStyle::CE_CheckBox, &option, painter);
        }
    }
     
    void MyQHeaderView::mousePressEvent(QMouseEvent *event)
    {
        if (isEnabled() && logicalIndexAt(event->pos()) == 0)
        {
            m_isOn = !m_isOn;
            updateSection(0);
            emit headCheckBoxToggled(m_isOn);
        }
        else QHeaderView::mousePressEvent(event);
    }
     
    QRect MyQHeaderView::checkBoxRect(const QRect &sourceRect) const
    {
        QStyleOptionButton checkBoxStyleOption;
        QRect checkBoxRect = style()->subElementRect(QStyle::SE_CheckBoxIndicator,
                                                     &checkBoxStyleOption);
        QPoint checkBoxPoint(sourceRect.x()+5,
                             sourceRect.y() +
                             sourceRect.height() / 2 -
                             checkBoxRect.height() / 2);
        return QRect(checkBoxPoint, checkBoxRect.size());
    }
    使用自定义表头:
    MyQHeaderView*myHeader=new MyQHeaderView(Qt::Horizontal, ui->tableWidgetCourseList);
    ui->tableWidgetCourseList->setHorizontalHeader(myHeader);
    为QTableWidget添加一行数据实际上是根据行数和列数,循环QTableWidget的所有单元格,对每个单元格item设置数据来实现的。
    似乎Qt中new出来的控件类型都只负责new不用delete的,感到很奇怪,后来经过查资料发现很多人有同样的疑问,有人给出原因是因为Qt中的所有的控件类是继承自QObject类,如果在new的时候指定了父亲(在构造函数的参数中有parent这个参数),那么它的清理是在其父亲被delete的时候被delete的。Qt不建议程序员在代码中手工delete一个QObject,如果一定要这么做,需要使用QObject的deleteLater()函数,否则可能出现Qt正在一级一级的从一个父亲类开始清理下面的所有子对象的时候,程序中手工调用delete也去清理其中的子对象,那么这个时候就可能出现问题,所以建议使用deleteLater()函数,它会让所有事件都发送完成之后再清理该片内存。
    QT的线程

Qt的线程

使用起来非常简单,我们首先要建立一个自定义的类(例如MyThread),继承自QThread,并实现其run方法即可。在使用线程的时候直接得到MyThread的实例,调用其start()函数即可启动线程,线程启动之后会自动调用其实现的run方法,该方法就是线程的执行函数,我们的线程任务就写在这里,当run退出之后线程基本就结束了,QThread有一个started和finished信号,我们可以为这两个信号指定槽函数,在线程启动和结束的时候执行一段代码进行资源的初始化和资源的释放操作。

TableView技巧

tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

(参数含义:QAbstractItemView.NoEditTriggers–不能对表格内容进行修改

QAbstractItemView.CurrentChanged–任何时候都能对单元格修改

QAbstractItemView.DoubleClicked–双击单元格

QAbstractItemView.SelectedClicked–单击已选中的内容

QAbstractItemView.EditKeyPressed–

QAbstractItemView.AnyKeyPressed–按下任意键就能修改

QAbstractItemView.AllEditTriggers–以上条件全包括)
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式

(参数含义:AbstractItemView.SelectItems–选中单个单元格

QAbstractItemView.SelectRows–选中一行

QAbstractItemView.SelectColumns–选中一列)
tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); //设置为可以选中多个目标

(参数含义:QAbstractItemView.NoSelection–不能选择

QAbstractItemView.SingleSelection–选中单个目标

QAbstractItemView.MultiSelection–选中多个目标

QAbstractItemView.ExtendedSelection/QAbstractItemView.ContiguousSelection 的区别不明显,主要功能是正常情况下是单选,但按下Ctrl或Shift键后,可以多选)
tableWidget->verticalHeader()->setVisible(false); //隐藏列表头

tableWidget->horizontalHeader()->setVisible(false); //隐藏行表头
QTableWidgetItem *columnHeaderItem0 = tableWidget->horizontalHeaderItem(0); //获得水平方向表头的Item对象

columnHeaderItem0->setFont(QFont(“Helvetica”)); //设置字体

columnHeaderItem0->setBackgroundColor(QColor(0,60,10)); //设置单元格背景颜色

columnHeaderItem0->setTextColor(QColor(200,111,30)); //设置文字颜色
单元格中添加图片
tableWidget->setItem(row, 0, new QTableWidgetItem(QIcon(“:/new/images/kingdemo.ico”),tr(“”)));
单元格字体颜色
QTableWidgetItem *item = new QTableWidgetItem(“Apple”);
item->setBackgroundColor(QColor(0,60,10));
item->setTextColor(QColor(200,111,100));
item->setFont(QFont(“Helvetica”));
tableWidget->setItem(0,3,item);
设置单元格的大小
//首先,可以指定某个行或者列的大小
tableWidget->setColumnWidth(3,200);

tableWidget->setRowHeight(3,60);
//还可以将行和列的大小设为与内容相匹配

tableWidget->resizeColumnsToContents();

tableWidget->resizeRowsToContents();
12.获得单击单元格的内容
通过实现 itemClicked (QTableWidgetItem *) 信号的槽函数,就可以获得鼠标单击到的单元格指针,进而获得其中的文字信息

connect(tableWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(getItem(QTreeWidgetItem*,int)));
13.QTableWidget要调整表格行宽主要涉及以下函数
tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);//使列完全填充并平分

tableWidget->verticalHeader()->setResizeMode(QHeaderView::Stretch);//行自适应宽度

tableWidget->resizeColumnsToContents(); //根据内容调整列宽

tableWidget->resizeColumnToContents(int col);//根据内容自动调整给定列宽

tableWidget->horizontalHeader()->setResizeMode//把给定列设置为给定模式

//主要模式有Stretch和Fixed
15.清除
tableWidget->clear();//清除所有可见数据(包括表头),行还在

tableWidget->clearContents();//只清除表中数据,不清除表头内容

tableWidget->setRowCount(0);//连行也清除掉
16.排序
tableWidget->sortByColumn(0, Qt::AscendingOrder);//顾名思义,该函数意思是将某列按升序/降序的方式排列
int row = tableWidget->rowCount();//获取表格中当前总行数

TableView常用方法

  tableWidget->setRowCount(row+1);//添加一行

  tableWidget->removeRow(row);//清除已有的行列

  Int row1 = tableWidget->currentItem()->row();//当前选中行

  bool focus = tableWidget->isItemSelected(tableWidget->currentItem());//判断是否选中一行

  QString proName = tableWidget->item(row, col)->text();//获取某一格内容

  setShowGrid(true);//显示表格线

  verticalHeader()->setVisible(false);//隐藏左边垂直

  QHeaderView *headerView = horizontalHeader();

  headerView->setMovable(false);//去除表头的移动

  headerView->resizeSection(0,284);//设置第一列宽

  headerView->resizeSection(1,127);//设置第二列宽

  headerView->setResizeMode(QHeaderView::Fixed);//列表不能移动

  headerView->setClickable(false);//不响应鼠标单击

  setEditTriggers(QTableWidget::NoEditTriggers);//不能编辑

  setSelectionBehavior(QTableWidget::SelectRows);//一次选中一行

  setSelectionMode(QAbstractItemView::SingleSelection);//只能单选

  /*QScrollBar *scrollBar = horizontalScrollBar();

  scrollBar->hide();*/

  setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//去掉水平滚动条

  setVerticalScrollMode(QAbstractItemView::ScrollPerItem);//垂直滚动条按项移动

  setAutoScroll(false);//去掉自动滚动

自适应宽度

ui.Retina_1->horizontalHeader()->setStretchLastSection(true);
ui.Retina_1->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

设置默认高度

ui.Retina_1->verticalHeader()->setDefaultSectionSize(25);

隐藏滚动条

ui.Retina_1->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui.Retina_1->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

ui.Retina_1->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
ui.Retina_1->setSelectionMode(QAbstractItemView::NoSelection);//不可选择
ui.Retina_1->verticalHeader()->setVisible(false); //隐藏列表头

QLineEdit

1.void setClearButtonEnabled(bool); //是否设置一个清空按钮.
2.void setEchoMode(QLineEdit::EchoMode); //设置行编辑框内文本的显示模式.
3.void setAlignent(Qt::Alignment flag); //设置文本输入的位置.
4.void setValidator(QVaildator*); //设置输入验证器
5.void setPlaceText(QString); //设置占位符.
7.void setReadOnly(bool); //把该行编辑框设置为只读模式,无法进行编辑.
3.void selectAll(); //选中框内所有文本.
信号:
1.void cursorPositionChanged(int old, int new); //光标位置改变就发现信号.
2.void returnPressed(); //光标在行编辑框内时,点击回车即发出信号.
3.void selectionChanged() //选择的文本发生变化时,发出信号.
4.void textChanged(const QString & text) //文本发生变化时,发出信号.

表格控件根据内容自动调整宽度和高度

ui->tableView->resizeColumnsToContents();

ui->tableView->resizeRowsToContents();

其他类

QFileInfo 显示文件信息类:主要作用是显示文件名字和文件路径,当然还有文件大小和最近修改时间(还有绝对路径和相对路径的关系)

QNetWorkInterface 提供网络接口 获取ip地址

QNetworkRequest QNetworkReply QNetworkAccessManager 构建HTTP客户端

QMatrix 指定坐标系的2D变换–> 平移 纵移 缩放 旋转 通常在渲染图像的时候使用

QTextCodeC qt中用来进行编码转换的类(unicode和其他编码方式转换)

QSqlQuery 这个类封装了基本数据的一些基本语法操作(增删改查),自动识别select等语句,返回true或者false报告状态

QSqlRecord 这个类封装了数据库的记录功能和特性。能从记录的数据中删除和添加字段,并且支持字段的查找功能(记录都是一条一条的) 

透明度

QPushButtonBox 这个类比单纯的使用pushbutton更加方便且更加美观。可以尝试使用这个类
控件设置透明度:

QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(this);

effect->setOpacity(0.9); //设置透明度 ui->widget->setGraphicsEffect(effect); //加在需要设置透明的控件上

 控件设置圆角边框:

 //通过控件的样式表即可实现

 ui->widget->setStyleSheet(“border-radius:3px;”);
 控件重叠,即实现控件“浮动效果”:

   在界面存在布局的情况下,是无法将连个控件重叠在一起的,如果我们要实现界面中一部分控件“浮动”其他控件上的效果,可以通过栈布局的方式来实现。然而在默认情况下,栈布局同时只能显示一帧画面,要做到栈布局中所有控件同时显示,要用到一下代码:

 QStackedLayout*laylout=(QStackedLayout*)ui->stackedWidget->layout();

 laylout->setStackingMode(QStackedLayout::StackAll);
 QLabel标签添加点击事件:

   QLabel没有特定的信号槽来让我们处理点击事件,需要通过一下方法:

 为标签绑定点击事件的监听函数

 ui->label ->installEventFilter(this);

 重写窗体类的eventFilter()函数

 bool MainForm::eventFilter(QObject *obj, QEvent *event){

 if(obj==ui->label){

    //过滤出单击事件

         if (event->type() == QEvent::MouseButtonPress) {

              //处理函数

             return true;

         }

 }

 //其他判断…

     return QWidget::eventFilter(obj,event);

 }
 QLabel 同时显示文字和图片:

   QLabel 在QDisginer编辑时可以通过属性窗口设置图片和文字,但最终程序运行时是不会同时显示的,即这两个属性会相互覆盖,只显示其一。为达到图文同时显示,可通过重载QLabel的 paintEvent()函数来实现,若我们在属性中设置好了图片,需显示额文字,可通过以下方法:

 void QCustLabel::paintEvent(QPaintEvent *event){

     //先按默认防止进行标签绘制

     QLabel::paintEvent(event);

 QPainter painter(this);

 //设置文字颜色

     painter.setPen(Qt::white);

     //要显示的可以作为一个成员变量

 QString info=this->desInfo;

 //设置文字信息的x坐标和y坐标

 //此处用了水平居中和垂直居中

     int x=this->width()/2-(this->fontMetrics().width(info)/2);

 int y=this->height()/2+(this->fontMetrics().height()/2);

 //绘出文字

     painter.drawText(QPoint(x,y),info);

 }
   此方法中用到了 Qt的二维绘图类 QPainter,此处使用的方法还是比较简单的,关于QPainter使用总结,会在接下来的文章中给出。

 由此,我们可以在label中随意指定文字、图片的显示方式。
 

一. 背景刷成黑色,前景色设为白色。
方法一、paltette方式,经测试,该方法不会影响到其他控件,推荐使用
QPalette bgpal = palette();
bgpal.setColor (QPalette::Background, QColor (0, 0 , 0, 255));
//bgpal.setColor (QPalette::Background, Qt::transparent);
bgpal.setColor (QPalette::Foreground, QColor (255,255,255,255)); setPalette (bgpal);
setStyleSheet (“background-color: rgb(0,0,0);color: rgb(255,255,255);”);
setStyleSheet (“venus–TitleBar {background-color: rgb(0,0,0);color: rgb(255,255,255);}”);
this->setObjectName(“pw”);// 设置对象句,相当于css里的id
this->setStyleSheet(“#pw {border-image: url(:/new/prefix1/Pic/54.png);}”);// 设置id对应元素的背景色
setStyleSheet (“border:2px groove gray;border-radius:10px;padding:2px 4px;”); // 圆角矩形
圆角窗口

点击(此处)折叠或打开

RoundRectWin::RoundRectWin()
{
QPalette p = palette();
QPixmap img(“roundrect.png”);
QBitmap mask(“roundrect_mask.png”);
p.setBrush(QPalette::Window, QBrush(img));
setPalette(p);
setMask(mask);
resize(img.size());
//setWindowFlags(Qt::FramelessWindowHint);//这句会去掉标题栏 } 注意:mask的图多余部分设为白色
}

半透明窗口

1.窗口整体透明,但是窗体上的控件不透明。 通过设置窗体的背景色来实现,将背景色设置为全透。

QPalette pal = palette();
pal.setColor(QPalette::Background, QColor(0x00,0xff,0x00,0x00));
setPalette(pal);
//窗体标题栏不透明,窗体客户区上的控件不透明
setAttribute(Qt::WA_TranslucentBackground, true);
//2.窗口及其上面的控件都半透明
setWindowOpacity(0.7);
窗口整体不透明,局部透明
void TestWindow::paintEvent( QPaintEvent* )
{
QPainter p(this);
p.setCompositionMode( QPainter::CompositionMode_Clear );
p.fillRect( 10, 10, 300, 300, Qt::SolidPattern );
}
控制QPixmap的alpha

QPixmap temp(pixmapTop.size()); temp.fill(Qt::transparent);
QPainter p(&temp);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, 0, pixmapTop);
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.fillRect(temp.rect(), QColor(0, 0, 0, alpha)); //–lable显示前景图片 ui->label->setScaledContents(true);
ui->label->setPixmap(temp);
layout 的边界
layout->setMargin (0);
qt 设置子控件为半透明和背景色问题

在子widget的构造函数里添加如下几句: 

QPalette myPalette;
QColor myColor(0,0,0);
myColor.setAlphaF(0.2);
myPalette.setBrush(backgroundRole(),myColor);
this->setPalette(myPalette);
this->setAutoFillBackground(true);
原理是:改子widget的背景色+修改alpha值(设置半透明)
改子widget的背景色 :
QPalette myPalette;
QColor myColor(0,0,0);
myPalette.setBrush(backgroundRole(),myColor);
this->setPalette(myPalette);
this->setAutoFillBackground(true);//这句很关键,缺少的话,背景色修改不成功
背景图片

QPixmap pixmap(“:/images/*.png”); 
  setMask(pixmap.mask()); 
QPalette palette; 
palette.setBrush(QPalette::Background, QBrush( pixmap ) ); 
setPalette(palette); 
resize( pixmap.size() ); 
setMask(pixmap.mask());