挂件:
QLabel
QLineEdit
QTabWidget
QTableWidget
QGroupBox
QCheckBox
QRadioBotton QAbstractBotton
QPushBotton
布局
QHBoxLayout horizontal
QVBoxLayout vertival
QFont font ( "Microsoft YaHei", 10, 75);//第一个属性是字体(微软雅黑),第二个是大小,第三个是加粗(权重是75)
ui->label->setFont(font);
常见权重
QFont::Light - 25 高亮
QFont::Normal - 50 正常
QFont::DemiBold - 63 半粗体
QFont::Bold - 75 粗体
QFont::Black - 87 黑体
QFont font1("Fantasy",24);//设置字体格式以及大小
label1->setFont(font1);
label1->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);//设置居中
label1->setText(tr("点击↓开始"));//设置文字
QGridLayout *layout = new QGridLayout(this);
layout->addWidget(label1, 0 ,1);//布局加部件
layout->addWidget(btn1, 1, 1);
layout->setSizeConstraint(QLayout::SetFixedSize);//设置合适尺寸
QHBoxLayout *Leftlayout = new QHBoxLayout;
//设置0,1两列的所占比例
Leftlayout->setColumnStretch(0,1);
Leftlayout->setColumnStretch(0,3);
//设置占几行,占几列
Leftlayout->addWidget(OtherLabel,5,0,1,2);
//设置固定大小
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setMaximumSize(393,171);
this->setMinimumSize(393,171);
}
//设置图片Label
HeadLabel = new QLabel(tr("头像"));
HeadIconLabel = new QLabel;
QPixmap icon("1.png");
HeadIconLabel->setPixmap(icon);//label显示图像
HeadIconLabel->resize(icon.width(),icon.height());//设置lable和头像一些养大
//设置间距
TopRightLayout = new QHBoxLayout();
TopRightLayout->setSpacing(20);
//设置边距
TopRightLayout = new QHBoxLayout();
TopRightLayout->setMargin(10);
//设置占位符
ButtonLayout = new QHBoxLayout();
ButtonLayout->setStretch();
ButtonLayout->addWidget(OkBtn);
//设置文件打开对话窗口
QString s = QFileDialog::getOpenFileName(this, "open file", "c:","C++ files(*.cpp);;C files(*.c);;Head files(*.h)");
if(!s.isEmpty)
setWindowTitle(s);
//设置消息对话框
if( QMessageBox::question(this, "问题","有个问题要问你",QMessageBox::Ok | QMessageBox::Cancle,QMessageBox::Ok) == QMessageBox::Ok )
{
}
else
{
}
toolBtn1=new QToolButton();
toolBtn1->setText("张三");//设置QToolButton按钮标题
toolBtn1->setIcon(QPixmap("1.png"));//设置QToolButton的图像
toolBtn1->setIconSize(QPixmap("1.png").size());//设置QToolButton的大小和图像一致
toolBtn1->setAutoRaise(true);//设置QToolButton按钮自动弹起
toolBtn1->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);//设置文字在图片的旁边
#include <QFile>
#include <QTextStream>
//设置文件打开对话窗口
QString file = QFileDialog::getOpenFileName();
QFile file(filename);
if(file.open(QFile::ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
s = stream.readLine();
QMessageBox::information(this, "文件内容", s);
}
file.close();
}
//设置menubar
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
open = new QAction(tr("打开"),this);
open->setShortcut(tr("Ctrl+O"));//设置快捷键
fileexit = new QAction(tr("退出"),this);
fileexit->setShortcut(tr("Ctrl+E"));
menu = menuBar()->addMenu(tr("文件"));
menu->addAction(open);
menu->addSeparator();
menu->addAction(fileexit);
menu = menuBar()->addMenu(tr("About"));
edit1 = new QTextEdit;
setCentralWidget(edit1);
connect(open, SIGNAL(triggered()), this, SLOT(openfile()));
}
//关闭事件
void MainWindow::closeEvent(QCloseEvent *event)
{
QMessageBox::StandardButton button = QMessageBox::question(this, tr("退出程序"),QString(tr("是否退出")),
QMessageBox::Yes|QMessageBox::No,QMessageBox::No);
if(button == QMessageBox::Yes)
{
event->accept();
}
else
{
event->ignore();
}
}
//设置textedit光标位置
QTextCursor cursor = textEdit->textCursor();
cursor.movePosition(QTextCursor::Start);
textEdit->setTextCursor(cursor);
//获取host信息
QT如果要进行网络编程首先需要在.pro中添加如下代码:
QT += network
在头文件中包含相关头文件
#include <QHostInfo>
#include <QNetworkInterface>
void Widget::btn_click()
{
//获取主机名称
QString s=QHostInfo::localHostName();
//根据主机名获取主机其他信息
QHostInfo info=QHostInfo::fromName(s);
/*获取主机所有的网络地址,IP地址跟网卡有关系,一个主机可能存在多个网卡或者虚拟机网卡*/
QList<QHostAddress> list=info.addresses();
if(!list.isEmpty())
{
/*设置一个迭代器*/
QList<QHostAddress>::iterator i;
for(i=list.begin();i!=list.end();i++)
{
QMessageBox::information(this,"主机地址",(*i).toString());
}
}
label1->setText(s);
}
void Widget::btn_click()
{
QString detail;
/*得到本机所有的网络接口信息*/
QList<QNetworkInterface> list=QNetworkInterface::allInterfaces();
QList<QNetworkInterface>::iterator i;
for(i=list.begin();i!=list.end();i++)
{
QNetworkInterface interface=*i;
/*获取设备名字*/
detail=tr("设备:")+interface.name()+"\n";
detail+=tr("硬件地址:")+interface.hardwareAddress()+"\n";
QList<QNetworkAddressEntry> entrylist=interface.addressEntries();
QList<QNetworkAddressEntry>::iterator j;
for(j=entrylist.begin();j!=entrylist.end();j++)
{
//
QNetworkAddressEntry entry=*j;
detail+="\t"+tr("IP地址:")+entry.ip().toString()+"\n";
detail+="\t"+tr("子网掩码:")+entry.netmask().toString()+"\n";
detail+="\t"+tr("广播地址:")+entry.broadcast().toString()+"\n";
}
QMessageBox::information(this,"主机信息",detail);
}
}
//重定向cmd
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QString cmd;
cmd = edit1->text();
QProcess p2(0);
p2.start("cmd", QStringList()<<"/c"<<cmd);
p2.waitForStarted();
p2.waitForFinished();
QString strTemp=QString::fromLocal8Bit(p2.readAllStandardOutput());
label1 = new QLabel(this);
label1->setText(strTemp);
}
//设置label颜色
QPalette pe;
pe.setColor(QPallette::WindowText,Qt::red);
label0->setPalette(pe);
label0->setText(tr("请输入命令"));
//设置dialog背景图片
this->setAutoFillBackground(true);
QPalette palette;
palette.setBrush(QPalette::Background, QBrush(QPixmap("2.jpg")));
setPalette(palette);
//设置scrollArea
scrollArea = new QScrollArea;
scrollArea->setBackgroundRole(QPalette::Base);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scrollArea->setWidget(recv);
//设置UTF8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
TCP-client:
//连接
serverip=new QHostAddress();
serverip->setAddress(ipaddr);
tcpsocket->connectToHost(*serverip,port.toInt());
//发送
QString strtext=edit3->text();
if(!strtext.isEmpty())
tcpsocket->write(strtext.toStdString().data());
//接收消息
void Widget::myrecvdata()
{
char buf[1024]={0};
/*bytesAvailable()表示有效数据*/
while(tcpsocket->bytesAvailable()>0)
{
memset(buf,0,sizeof(buf));
tcpsocket->read(buf,sizeof(buf));
textb->append(buf);
//QMessageBox::information(this,"消息",buf);
}
}
//设置最大化最小化按钮无效
setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint);
//设置不在任务栏出现
setWindowFlags(windowFlags() | Qt::Tool);
////隐藏最大化按钮
this->setWindowFlags(this->windowFlags()&~Qt::WindowMaximizeButtonHint);
//去掉问号
Qt::WindowFlags flags=Qt::Dialog;
flags |=Qt::WindowCloseButtonHint;
setWindowFlags(flags);
//当前时间
QString curTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
//设置文件过滤器
void MainWindow::savefile()
{
QFileDialog dialog(this,"保存文件","C:\\Users\\Administrator\\Desktop"
,tr("富文本(*.rtf);;纯文本(*.txt)"));
QString filterMod;
QString fileName;
if(dialog.exec())
{
fileName = dialog.selectedFiles()[0];
filterMod = dialog.selectedNameFilter();
}
QFile file(fileName);
if(file.open(QFile::WriteOnly |QFile::Truncate))
{
QTextStream stream(&file);
if("富文本(*.rtf)" == filterMod)
stream<<textEdit->toHtml();
if("纯文本(*.txt)" == filterMod)
stream<<textEdit->toPlainText();
}
file.close();
}
//设置颜色字体
void MainWindow::colslot()
{
const QColorDialog::ColorDialogOptions options = QFlag(QColorDialog::ShowAlphaChannel);
const QColor color = QColorDialog::getColor(Qt::green, this, "Select Color", options);
if (color.isValid())
{
textEdit->setTextColor(color);
}
}
void MainWindow::fontslot()
{
bool ok;
QFont font = QFontDialog::getFont(
&ok, QFont("Helvetica [Cronyx]", 10), this);
if (ok)
{
textEdit->setFont(font);
} else
{
;
}
}
//设置光标的选区,使格式作用于选区内的字符
void MainWindow::mergeFormat(QTextCharFormat fmt)
{
QTextCursor cursor = textEdit->textCursor();
if (!cursor.hasSelection()) {
cursor.select(QTextCursor::WordUnderCursor);
}
cursor.mergeCharFormat(fmt);
}
//设置分隔字符串
QString mainPage = "mainpage=http://www.baidu.com"
QStringList list = mainPage.split("=");
//捕获消息
void event(QEvent* ev);
bool MyWidget::event(QEvent* ev)
{
//消息被截断
if(ev.type == QEvent::MouseButtonPress)
return true;
//如果不是鼠标消息,就继续传递消息
return QWidget::event(ev);
}
//重载具体的虚函数,处理鼠标事件
#include <QMouseEvent>
void mousePressEvent(QMouseEvent* ev);
void mouseReleaseEvent(QMouseEvent* ev);
void mouseMoveEvent(QMouseEvent* ev);
bool MyWidget::mousePressEvent(QMouseEvent* ev)//重载
{
QPoint pt = ev->pos();
qDebug()<< pt;
if(ev->button() == Qt::LeftButton)
{
....
}
//shift被按下
if(ev->modifiers() == Qt::ShiftModifier)
{
....
}
}
//鼠标消息,键盘消息
#include <QKeyEvent>
void keyPressEvent(QMouseEvent* ev);
{
ev->modifiers();
int key = ev->key();
qDebug() << (char)key;
}
void keyReleaseEvent(QMouseEvent* ev);
//鼠标不需要按下,就得到消息
this->setMousetTracking(true);
//传递消息第一种方式,消息过滤器
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
QPushButton* button;
button = new QPushButton("This button", this);
connect(button, SIGNAL(clicked()), this, SLOT(close()));
_button = button;
/* button给自己安装了一个消息过滤器,那么经过button的消息,都先要调用它的过滤器的eventFilter函数 */
button->installEventFilter(this);
}
bool MyWidget::eventFilter(QObject *o, QEvent *e)
{
#if 0
if(o == (QObject*)_button &&(
e->type() == QEvent::MouseButtonRelease ||
e->type() == QEvent::MouseButtonDblClick ||
e->type() == QEvent::MouseButtonPress))
{
return true;
}
#endif
return QWidget::eventFilter(o, e);
}
//传递消息第二种方式,App消息通知
bool MyApplication::notify(QObject *o, QEvent *e)
{
if(this->topLevelWidgets().count()>0)
{
QWidget* mainWnd = this->topLevelWidgets().at(0);
if(o==(QObject*)mainWnd && e->type() == QEvent::MouseButtonPress)
{
// do ...
qDebug() << "mainwnd is clicked";
}
}
return QApplication::notify(o, e);
}
//传递消息第三种方式,自定义消息
bool MyWidget::event(QEvent *e)
{
if(e->type() == QEvent::User)
{
qDebug() << "User event is comming";
}
return QWidget::event(e);
}
int main(int argc, char* argv[])
{
MyApplication app(argc, argv);
MyWidget w;
w.show();
// 发送一个Event给MyWidget
qDebug() << "begin send";
app.postEvent(&w, new QEvent(QEvent::User));
qDebug() << "end send";
// app.sendEvent(&w, )
return app.exec();
}
Qt 知识点收集(一)
最新推荐文章于 2023-10-10 22:56:02 发布