Summary of Qt interface development problems

Window minimization, maximization button customization

setWindowFlags(Qt::CustomizeWindowHint);
setWindowFlags(Qt::WindowCloseButtonHint); // 只要关闭按钮
setWindowFlags(Qt::WindowFlags type)

Full screen display and restoration

1. Block the taskbar

// 这两个都可以!
showFullScreen(); // 设置窗口全屏显示
showMaximized(); // 设置窗口最大化显示

2. Does not block the taskbar

void showMaximize()
{
    
    
    // 若已经最大化
    if(is_max)
    {
    
    
        // 恢复界面位置,并设置按钮图标为最大化图标,提示“最大化”
        this->setGeometry(location);
        max_button->setIcon(QIcon("maxbtn"));
        max_button->setToolTip(tr("max"));
    } 
    else 
    {
    
    
        // 设定当前界面的位置,还原时使用
        location = this->geometry();
        // 获取桌面位置,设置为最大化,并设置按钮图标为还原图标,提示“还原”
        QDesktopWidget *desk = QApplication::desktop();
        this->setGeometry(desk->availableGeometry());
        max_button->setIcon(QIcon("restorbtn"));
        max_button->setToolTip(tr("restor"));
    }
    is_max = !is_max;
}

Note: Since the window can be maximized, it must be restored of course. is_max is a bool value variable, indicating whether the window is maximized, and the initial value is false. location is the location of the desktop. Every time it is maximized, it will record the current location and wait for it to be used when restoring.
extension:

isFullScreen(); // 判断窗口当前是处于全屏状态还是非全屏状态
showNormal(); // 设置窗口恢复原来显示

hide taskbar display

setWindowFlags(Qt::Tool | Qt::X11BypassWindowManagerHint);

Draw the background image and achieve the rounded corner effect

void paintEvent(QPaintEvent *)
{
    
    
    QPainter painter(this);
    QBrush brush;
    brush.setTextureImage(QImage(background_image)); // 背景图片
    painter.setBrush(brush);
    painter.setPen(Qt::black);  // 边框色
    painter.drawRoundedRect(this->rect(), 5, 5); // 圆角5像素
}

Qt sets the window to be transparent

1. Fully transparent
setWindowOpacity(double value). This function is used to set the transparency of the form, the valid range is from 1.0 to 0.0, and it will affect child controls. By default, the value of this property is 1.0 (opaque).

this->setWindowOpacity(0.7);

2. Sub-controls are transparent
Use the Qt style sheet, background:rgba(r, g, b, opacity), rgb is the color value, opacity is the transparency set to translucent, and the valid range is from 1.0 to 0.0. Use a style sheet to set a background image, as well as the transparency of the widget and label (to set the transparency, specify the object to avoid affecting other controls)

//子控件透明
this->setStyleSheet("#centralWidget{border-image:url(://timg.jpg);}"
"#label{background:rgba(255,255,0,0.4);}"
"#widget{background:rgba(255,0,0,0.3);}");

3. The parent window is transparent

Situation 1: There is no picture in the background. Set the property Qt::WA_TranslucentBackground to make MainWindow fully transparent. On windows, this property needs to be used with Qt::FramelessWindowHint. Then set the opacity in the centralWidget style to adjust the transparency of the parent window and set the opacity of the child control.

this->setWindowFlags(Qt::FramelessWindowHint);//需要去掉标题栏
this->setAttribute(Qt::WA_TranslucentBackground);
this>setStyleSheet("#centralWidget{background:rgba(0,255,255,0.4);}"
"#label{background:rgba(255,255,0,1);}"
"#widget{background:rgba(0,255,255,1);}");

Case 2: There is a picture in the background. Still use the attribute Qt::WA_TranslucentBackground to make MainWindow fully transparent. Then draw the picture on the form in the paintevent and set the transparency.

void MainWindow::paintEvent(QPaintEvent *event)
{
    
    
    QPainter painter(this);
    QPixmap pix("://timg.jpg");
    QPixmap scalePix = pix.scaled(this->width(), this->height(),
        Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    painter.setOpacity(0.4);
    painter.drawPixmap(0, 0, scalePix);
}

Note: If setting the background attribute fails, you can try to set this attribute to solve setAttribute(Qt::WA_StyledBackground);.

Set the application's font

QFont font("Courier", 10, QFont::Normal, false);
QApplication::setFont(font);

Two implementations of Qt borderless window

setWindowFlags(Qt::CustomizeWindowHint);
setWindowFlags(Qt::FramelessWindowHint);

Both functions can remove the title bar, the difference is that the first one can zoom the window with the mouse.

Qt sets the active window

Encountered a Qt window problem and recorded that the displayed window was blocked by other windows. Calling show again cannot activate the window to the front. The solution is as follows:

if(!this->isActiveWindow()) //判断是否是活动窗口
{
    
    
    this->activateWindow(); //设置成活动窗口
}

How to tell if a window is closed

bool QWidget::isVisible(); // 窗口显示返回true

bool QWidget::isHidden(); // 窗口隐藏返回true

If the widget is set with Qt::WA_DeleteOnClose, the widget will be deleted when calling close(). In this case, a flag can be used to record and judge externally.

Free memory when the window is closed

When the user closes the window, its default behavior is to hide, so it will remain in memory. The solution is to add this sentence to the constructor:

setAttribute(Qt::WA_DeleteOnClose);

The t::WA_DeleteOnClose attribute is one of the flags that can be set on a QWidget and affect the widget's behavior.

Qt capture window close event

Sometimes we want to do some operations before closing the window, such as saving cached data or prompting the user whether to close the window, etc. Since general windows are inherited from QWidget, we can achieve this goal by overriding the virtual function closeEvent(QCloseEvent* event); in QWidget.

void MainWindow::closeEvent(QCloseEvent *event)  
{
    
      
	QMessageBox::StandardButton button;  
    button=QMessageBox::question(this,tr("退出程序"),QString(tr("确认退出程序")),QMessageBox::Yes|QMessageBox::No);  

    if(button==QMessageBox::No)  
    {
    
      
        event->ignore(); // 忽略退出信号,程序继续进行  
    }  

    else if(button==QMessageBox::Yes)  
    {
    
      
        event->accept(); // 接受退出信号,程序退出  
    }  

    // TODO: 在退出窗口之前,实现希望做的操作  
}

Qt5 realizes that the mouse clicks outside the window to close the window

Method 1: Rewrite the window. This method is the simplest, but there is a disadvantage that this function needs to be rewritten for each window that needs to implement this function.

bool Form::event(QEvent *event)
{
    
    
    if (event->type() == QEvent::ActivationChange)
    {
    
    
        if(QApplication::activeWindow() != this)
        {
    
    
            this->close();
        }
    }
 
    return QWidget::event(event);
}

Method 2: Use event filters

Step 1: Install an event filter for each window that needs to implement this function, usually in the constructor:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    
    
    ui->setupUi(this);
    //f和f1都是窗口类实例
    f=new Form;
    f1=new Form1;
    f->installEventFilter(this);
    f1->installEventFilter(this);    
}

Step 2: Rewrite the event filter function:

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    
    
    if (event->type() == QEvent::ActivationChange)
    {
    
    
        if(watched == f || watched == f1)//需要实现该功能的控件
        {
    
    
            if(QApplication::activeWindow() != watched)
            {
    
    
                QWidget *w=static_cast<QWidget *>(watched);
                w->close();
            }
        }
    }
    return QWidget::eventFilter(watched, event);
}

Enter to exit the question

I created a new QDialog window, which has multiple QLabels, QLineEdit and an Exit button, but after editing the QLineEdit, the window exits immediately after pressing Enter. Later, I found out that the button is set to StrongFocus by default.

Solution:
Set the focusPolicy attribute of the exit button in the window to NoFocus.

Esc exit problem

Need to rewrite keyPressEvent() of QDialog:

#include <QKeyEvent>

void MyDialog::keyPressEvent(QKeyEvent *event)
{
    
    
    switch (event->key())
    {
    
    
    case Qt::Key_Escape:  // 按下的为Esc键
        break;  // 不做反应直接退出
    default:
        QDialog::keyPressEvent(event);
    }
}

QWidget sets the hierarchical relationship of controls

设置控件置于父窗口的顶部:widget->raise();

设置控件层次:widget->stackUnder(other_widget);

设置控件置于父窗口的底部:widget->lower();

Qt removes the dotted frame of controls such as buttons

Method 1: It can be set through the code ui->pushButton->setFocusPolicy(Qt::NoFocus) or in the property list of Qt Creator.

Method 2: If you need to switch controls through buttons in an embedded device, the easiest way is to achieve it through the focus of the control, and method 1 cannot be used. At this point, you can remove the dotted box through the qss style sheet, the code is as follows:

ui->pushButton->setStyleSheet("outline: none");  

Method 3: It is also implemented through the qss style sheet, the code is as follows:

ui->pushButton->setStyleSheet("padding: -1"); 

Guess you like

Origin blog.csdn.net/houxian1103/article/details/130141617