Exception open failed: EACCES (Permission denied) on Android

Exception open failed: EACCES (Permission denied) on Android

Exception open failed: EACCES (Permission denied) on Android

Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:

<manifest ... >
    <!-- This attribute is false by default on apps targeting Android Q. -->
    <application android_requestLegacyExternalStorage=true ... >
     ...
    </application>
</manifest>

You can read more about it here: https://developer.android.com/training/data-storage/use-cases

Edit: I am starting to get downvotes because this answer is out of date for Android 11. So whoever sees this answer please go to the link above and read the instructions.

For API 23+ you need to request the read/write permissions even if they are already in your manifest.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We dont have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

AndroidManifest.xml

<uses-permission android_name=android.permission.READ_EXTERNAL_STORAGE />
<uses-permission android_name=android.permission.WRITE_EXTERNAL_STORAGE />

For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html

Exception open failed: EACCES (Permission denied) on Android

I had the same problem… The <uses-permission was in the wrong place. This is right:

 <manifest>
        <uses-permission android_name=android.permission.WRITE_EXTERNAL_STORAGE/>
        ...
        <application>
            ...
            <activity> 
                ...
            </activity>
        </application>
    </manifest> 

The uses-permission tag needs to be outside the application tag.

Related posts on Android :

sql – snowflake substring by pattern

sql – snowflake substring by pattern

Use the REGEXP_SUBSTR(…) built-in function to extract substrings using a regular expression pattern.

If there will only be one number in each column value, a number pattern or a numeric characters range syntax will suffice:

SELECT
accountNumber:123456 i1,
regexp_substr(i1, [0-9]+) r1,
{accountNumber:123456} i2,
regexp_substr(i2, [0-9]+) r2;

+----------------------+--------+----------------------------+--------+         
| I1                   | R1     | I2                         | R2     |
|----------------------+--------+----------------------------+--------|
| accountNumber:123456 | 123456 | {accountNumber:123456} | 123456 |
+----------------------+--------+----------------------------+--------+

If the number will be exactly 6 digits wide, use the {n} repetition syntax:

select
accountNumber:123456,anotherNumber:123 i1,
regexp_substr(i1, [0-9]{6}) r1,
{accountNumber:123456, anotherNumber: 123} i2,
regexp_substr(i2,[0-9]{6}) r2;

+----------------------------------------+--------+--------------------------------------------------+--------+
| I1                                     | R1     | I2                                               | R2     |
|----------------------------------------+--------+--------------------------------------------------+--------|
| accountNumber:123456,anotherNumber:123 | 123456 | {accountNumber:123456, anotherNumber: 123} | 123456 |
+----------------------------------------+--------+--------------------------------------------------+--------+

If the number must only follow the text accountNumber, you can introduce (capture groups):

select
accountNumber:123456,anotherNumber:123,somethingElse:456789 i1,
regexp_substr(i1, accountNumber[: ]+([0-9]{6}), 1, 1, e, 1) r1,
{accountNumber:123456, anotherNumber: 123, somethingElse: 456789} i2,
regexp_substr(i2, accountNumber[: ]+([0-9]{6}), 1, 1, e, 1) r2;

+-------------------------------------------------------------+--------+---------------------------------------------------------------------------+--------+
| I1                                                          | R1     | I2                                                                        | R2     |
|-------------------------------------------------------------+--------+---------------------------------------------------------------------------+--------|
| accountNumber:123456,anotherNumber:123,somethingElse:456789 | 123456 | {accountNumber:123456, anotherNumber: 123, somethingElse: 456789} | 123456 |
+-------------------------------------------------------------+--------+---------------------------------------------------------------------------+--------+

Building a fully correct regular expression will require more knowledge about all of the variances possible in the data. Try building out your patterns interactively with a good test-set on sites such as Regex101, RegExr, etc. that make it easier to develop them.

Note: If your data is actually in a JSON format throughout, Snowflake permits parsing them into a VARIANT data type to query them more naturally:

select
parse_json({accountNumber:123456, anotherNumber: 123, somethingElse: 456789}):accountNumber::integer account_number;

+----------------+                                                              
| ACCOUNT_NUMBER |
|----------------|
|         123456 |
+----------------+

sql – snowflake substring by pattern

Read Also

Snowflake Substring

loops – C++ – using glfwGetTime() for a fixed time step

loops – C++ – using glfwGetTime() for a fixed time step

All you need is this code for limiting updates, but keeping the rendering at highest possible frames. The code is based on this tutorial which explains it very well. All I did was to implement the same principle with GLFW and C++.

   static double limitFPS = 1.0 / 60.0;

    double lastTime = glfwGetTime(), timer = lastTime;
    double deltaTime = 0, nowTime = 0;
    int frames = 0 , updates = 0;

    // - While window is alive
    while (!window.closed()) {

        // - Measure time
        nowTime = glfwGetTime();
        deltaTime += (nowTime - lastTime) / limitFPS;
        lastTime = nowTime;

        // - Only update at 60 frames / s
        while (deltaTime >= 1.0){
            update();   // - Update function
            updates++;
            deltaTime--;
        }
        // - Render at maximum possible frames
        render(); // - Render function
        frames++;

        // - Reset after one second
        if (glfwGetTime() - timer > 1.0) {
            timer ++;
            std::cout << FPS:  << frames <<  Updates: << updates << std::endl;
            updates = 0, frames = 0;
        }

    }

You should have a function update() for updating game logic and a render() for rendering. Hope this helps.

loops – C++ – using glfwGetTime() for a fixed time step

iterating over each character of a String in ruby 1.8.6 (each_char)

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

ABCDEFG.split().each do |i|
  puts i
end

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split().each { |i| yield i }
  end
end

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

ABCDEFG.each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end

Extending la_f0kas comment, esp. if you also need the index position in your code, you should be able to do

s = ABCDEFG
for pos in 0...s.length
    puts s[pos].chr
end

The .chr is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.

iterating over each character of a String in ruby 1.8.6 (each_char)

ABCDEFG.chars.each do |char|
  puts char
end

also

ABCDEFG.each_char {|char| p char}

Ruby version >2.5.1

java – SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

java – SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

You dont need to use Properties in your table data objects for them to display, although use of Properties in certain circumstances is desirable.

The following code will display a table of people based on a Person class which has only String fields.

import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class ReadOnlyTableView extends Application {
  private TableView<Person> table = new TableView<Person>();
  private final ObservableList<Person> data =
    FXCollections.observableArrayList(
      new Person(Jacob, Smith, [email protected]),
      new Person(Isabella, Johnson, [email protected]),
      new Person(Ethan, Williams, [email protected]),
      new Person(Emma, Jones, [email protected]),
      new Person(Michael, Brown, [email protected])
    );

  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    stage.setTitle(Table View Sample);
    stage.setWidth(450);
    stage.setHeight(500);

    final Label label = new Label(Address Book);
    label.setFont(new Font(Arial, 20));

    TableColumn firstNameCol = new TableColumn(First Name);
    firstNameCol.setMinWidth(100);
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(firstName));

    TableColumn lastNameCol = new TableColumn(Last Name);
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(lastName));

    TableColumn emailCol = new TableColumn(Email);
    emailCol.setMinWidth(200);
    emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>(email));

    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

    final VBox vbox = new VBox();
    vbox.setSpacing(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table);

    stage.setScene(new Scene(new Group(vbox)));
    stage.show();
  }

  public static class Person {
    private String firstName;
    private String lastName;
    private String email;

    private Person(String fName, String lName, String email) {
      this.firstName = fName;
      this.lastName = lName;
      this.email = email;
    }

    public String getFirstName() { return firstName; }
    public void setFirstName(String fName) { firstName = fName; }
    public String getLastName() { return lastName; }
    public void setLastName(String lName) { lastName = lName; }
    public String getEmail() { return email; }
    public void setEmail(String inMail) { email = inMail; }
  }
}

Explanation

The purpose of using Properties and ObservableLists is that these are listenable elements. When properties are used, if the value of a property attribute in the datamodel changes, the view of the item in the TableView is automatically updated to match the updated datamodel value. For example, if the value of a persons email property is set to a new value, that update will be reflected in the TableView because it listens for the property change. If instead, a plain String had been used to represent the email, the TableView would not refresh as it would be unaware of email value changes.

The PropertyValueFactory documentation describes this process in detail:

An example of how to use this class is:

TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>(First Name);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>(firstName));  

In this example, the firstName string is used as a reference to an
assumed firstNameProperty() method in the Person class type (which is
the class type of the TableView items list). Additionally, this method
must return a Property instance. If a method meeting these
requirements is found, then the TableCell is populated with this
ObservableValue. In addition, the TableView will automatically add an
observer to the returned value, such that any changes fired will be
observed by the TableView, resulting in the cell immediately updating.

If no method matching this pattern exists, there is fall-through
support for attempting to call get() or is() (that
is, getFirstName() or isFirstName() in the example above). If a method
matching this pattern exists, the value returned from this method is
wrapped in a ReadOnlyObjectWrapper and returned to the TableCell.
However, in this situation, this means that the TableCell will not be
able to observe the ObservableValue for changes (as is the case in the
first approach above).

Update

Here is a contrasting example to the first example which demonstrates how a TableView can observe and automatically refresh based on changes to its ObservableList of items and changes to the value of a property based item attribute.

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.collections.*;
import javafx.event.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class PropertyBasedTableView extends Application {
  private TableView<Person> table = new TableView<Person>();
  private final ObservableList<Person> data = FXCollections.observableArrayList();
  private void initData() {
    data.setAll(
      new Person(Jacob, Smith, [email protected]),
      new Person(Isabella, Johnson, [email protected]),
      new Person(Ethan, Williams, [email protected]),
      new Person(Emma, Jones, [email protected]),
      new Person(Michael, Brown, [email protected])
    );
  }

  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    initData();

    stage.setTitle(Table View Sample);
    stage.setWidth(450);
    stage.setHeight(500);

    final Label label = new Label(Address Book);
    label.setFont(new Font(Arial, 20));

    TableColumn firstNameCol = new TableColumn(First Name);
    firstNameCol.setMinWidth(100);
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(firstName));

    TableColumn lastNameCol = new TableColumn(Last Name);
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>(lastName));

    TableColumn emailCol = new TableColumn(Email);
    emailCol.setMinWidth(200);
    emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>(email));

    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
    table.setPrefHeight(300);

    final Button setEmailButton = new Button(Set first email in table to [email protected]);
    setEmailButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        if (data.size() > 0) {
          data.get(0).setEmail([email protected]);
        }  
      }
    });

    final Button removeRowButton = new Button(Remove first row from the table);
    removeRowButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        if (data.size() > 0) {
          data.remove(0);
        }  
      }
    });

    final Button resetButton = new Button(Reset table data);
    resetButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        initData();
      }
    });

    final VBox vbox = new VBox(10);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, table, setEmailButton, removeRowButton, resetButton);

    stage.setScene(new Scene(new Group(vbox)));
    stage.show();
  }

  public static class Person {
    private final StringProperty firstName;
    private final StringProperty lastName;
    private final StringProperty email;

    private Person(String fName, String lName, String email) {
      this.firstName = new SimpleStringProperty(fName);
      this.lastName = new SimpleStringProperty(lName);
      this.email = new SimpleStringProperty(email);
    }

    public String getFirstName() { return firstName.get(); }
    public void setFirstName(String fName) { firstName.set(fName); }
    public StringProperty firstNameProperty() { return firstName; }
    public String getLastName() { return lastName.get(); }
    public void setLastName(String lName) { lastName.set(lName); }
    public StringProperty lastNameProperty() { return lastName; }
    public String getEmail() { return email.get(); }
    public void setEmail(String inMail) { email.set(inMail); }
    public StringProperty emailProperty() { return email; }  // if this method is commented out then the tableview will not refresh when the email is set.
  }
}

java – SimpleStringProperty and SimpleIntegerProperty TableView JavaFX

java : convert float to String and String to float

java : convert float to String and String to float

Using Java’s Float class.

float f = Float.parseFloat(25);
String s = Float.toString(25.0f);

To compare its always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. 25 != 25.0 != 25.00 etc.)

Float to string – String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float – Float.parseFloat()

String strAmount=100.20;
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

java : convert float to String and String to float

You can try this sample of code:

public class StringToFloat
{

  public static void main (String[] args)
  {

    // String s = fred;    // do this if you want an exception

    String s = 100.00;

    try
    {
      float f = Float.valueOf(s.trim()).floatValue();
      System.out.println(float f =  + f);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println(NumberFormatException:  + nfe.getMessage());
    }
  }
}

found here

go – How to Create or Update a record with GORM?

go – How to Create or Update a record with GORM?

update 2020.10.09

Thanks for @vaelin

From 1.20.x on, GORM provides compatible Upsert support for different databases( Upsert-On-Conflict)

// Update columns to new value on `id` conflict
DB.Clauses(clause.OnConflict{
  Columns:   []clause.Column{{Name: id}}, // key colume
  DoUpdates: clause.AssignmentColumns([]string{name, age}), // column needed to be updated
}).Create(&users)
// MERGE INTO users USING *** WHEN NOT MATCHED THEN INSERT *** WHEN MATCHED THEN UPDATE SET name=excluded.name; SQL Server
// INSERT INTO users *** ON CONFLICT (id) DO UPDATE SET name=excluded.name, age=excluded.age; PostgreSQL
// INSERT INTO `users` *** ON DUPLICATE KEY UPDATE `name`=VALUES(name),`age=VALUES(age); MySQL

With gorm 1.9.x or below, its more effecient to update first, then insert when not existed.

// update only set name=nick
if err := db.Model(&newUser).Where(id = ?, 3333).Update(name, nick).Error; err != nil {
    // always handle error like this, cause errors maybe happened when connection failed or something. 
    // record not found...
    if gorm.IsRecordNotFoundError(err){
        db.Create(&newUser)  // create new record from newUser
    }
}

FirstOrInit and FirstOrCreate are different. If there is no match record in database, FirstOrInit will init struct but not create record, FirstOrCreate will create a record and query that record to struct.

The most upvoted answer did not work for me, but this did:

user := NewUser(email, password)
if db.Model(&user).Where(email = ?, email).Updates(&user).RowsAffected == 0 {
    db.Create(&user)
}

This works for gorm v1.9.15 and go 1.13

go – How to Create or Update a record with GORM?

gormDB.Where(entity.AggregatedData{Type: v.Type}).Assign(entity.AggregatedData{Type: v.Type, Data: v.Data}).FirstOrCreate(v)


 SELECT * FROM aggregated_data  WHERE (aggregated_data.type = 2) ORDER BY aggregated_data.id ASC LIMIT 1 

and if exist then

 UPDATE aggregated_data SET data = [{a:2}], type = 2  WHERE aggregated_data.id = 2 AND ((aggregated_data.type = 2))  

else

INSERT INTO aggregated_data (data,type) VALUES ([{a:2}],1) RETURNING aggregated_data.id  

apache spark – Difference in usecases for AWS Sagemaker vs Databricks?

apache spark – Difference in usecases for AWS Sagemaker vs Databricks?

SageMaker is a great tool for deployment, it simplifies a lot of processes configuring containers, you only need to write 2-3 lines to deploy the model as an endpoint and use it. SageMaker also provides the dev platform (Jupyter Notebook) which supports Python and Scala (sparkmagic kernal) developing, and i managed installing external scala kernel in jupyter notebook. Overall, SageMaker provides end-to-end ML services. Databricks has unbeatable Notebook environment for Spark development.

Conclusion

  1. Databricks is a better platform for Big data(scala, pyspark) Developing.(unbeatable notebook environment)
  2. SageMaker is better for Deployment. and if you are not working on big data, SageMaker is a perfect choice working with (Jupyter notebook + Sklearn + Mature containers + Super easy deployment).
  3. SageMaker provides real time inference, very easy to build and deploy, very impressive. you can check the official SageMaker Github.
    https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-python-sdk/scikit_learn_inference_pipeline

Having worked in both environments within the last year, I specifically remember:

  • Databricks having easy access to stored databases/tables to query out of and use Scala/Spark within the Jupyter Notebooks. I remember how nice it was to just see and preview the schemas and query quickly and be off to the races for research. I also remember the quick functionality to set up a timed job on a Notebook (re-run every month) and re-scale to job instance types (much cheaper) with some button clicks. These functionalities might exist somewhere in AWS, but I remember it being great in Databricks.
  • AWS SageMaker + Lambda + API Gateway: Legitimately, today, I worked through the deployment of AWS SageMaker + Lambda + API Gateway, and after getting used to some syntax and specifics of the Lambda + API Gateway it was pretty straightforward. Doing another AWS deployment wouldnt take more than 20 minutes (pending unique specificities). Other things like Model Monitoring and CloudWatch are nice as well. I did notice Jupyter Notebook Kernels for many languages like Python (what I did it in), R, and Scala, along with specific packages already pre-installed like conda and sagemaker ml packages and methods.

apache spark – Difference in usecases for AWS Sagemaker vs Databricks?

visual c++ – filling up an array in c++

visual c++ – filling up an array in c++

Using C++11

#include <algorithm>
#include <iostream>

int main() {
    char array[80];
    std::fill(std::begin(array),std::begin(array)+10,r);
}

Or, as mentioned in the comments you can use std::fill(array,array+10,r).

You can use the [] operator and assign a char value.

char y[80];
for(int b=0; b<10; ++b)
    y[b] = r;

And yes, std::fill is a more idiomatic and modern C++ way to do this, but you should know about the [] operator too!

visual c++ – filling up an array in c++

// ConsoleApp.cpp : Defines the entry point for the console application.
//

#include stdafx.h
#include <iostream>
#include <string>

using namespace std;

int fun(bool x,int y[],int length);
int funx(char y[]);
int functionx(bool IsMainProd, int MainProdId, int Addons[],int len);
int _tmain(int argc, _TCHAR* argv[])
{
    int AddonCancel[10];

    for( int i = 0 ; i<4 ;++i)
    {
        std::fill(std::begin(AddonCancel)+i,std::begin(AddonCancel)+i+1,i*5);
    }
    bool IsMainProduct (false);
    int MainProduct =4 ; 
    functionx(IsMainProduct,MainProduct,AddonCancel,4);

}

int functionx(bool IsMainProd, int MainProdId, int Addons[],int len)
{
    if(IsMainProd)
        std::cout<< Is Main Product;
    else
    {
        for(int x = 0 ; x<len;++x)
        {
          std::cout<< Addons[x];
        }
    }

    return 0 ; 
}

c++ – How do I render a triangle in QOpenGLWidget?

c++ – How do I render a triangle in QOpenGLWidget?

If you want to use QOpenGLWidget not QGLWidget, then this is the way to do it.

Open Qt Creator and choose Qt Widgets Application. Add Widget and push button as follows

enter

main.cpp

#include mainwindow.h
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.cpp

#include mainwindow.h
#include ui_mainwindow.h

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

mainwindow.h

#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:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

Now add New Class and name it OGLWidget which should be inherited from QOpenGLWidget

oglwidget.h

#ifndef OGLWIDGET_H
#define OGLWIDGET_H

#include <QWidget>
#include <QOpenGLWidget>
#include <gl/GLU.h>
#include <gl/GL.h>

class OGLWidget : public QOpenGLWidget
{
public:
    OGLWidget(QWidget *parent = 0);
    ~OGLWidget();

protected:
    void initializeGL();
    void resizeGL(int w, int h);
    void paintGL();
};

#endif // OGLWIDGET_H

oglwidget.cpp

#include oglwidget.h

OGLWidget::OGLWidget(QWidget *parent)
    : QOpenGLWidget(parent)
{

}

OGLWidget::~OGLWidget()
{

}

void OGLWidget::initializeGL()
{
    glClearColor(0,0,0,1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHTING);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    glEnable(GL_COLOR_MATERIAL);
}

void OGLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBegin(GL_TRIANGLES);
        glColor3f(1.0, 0.0, 0.0);
        glVertex3f(-0.5, -0.5, 0);
        glColor3f(0.0, 1.0, 0.0);
        glVertex3f( 0.5, -0.5, 0);
        glColor3f(0.0, 0.0, 1.0);
        glVertex3f( 0.0,  0.5, 0);
    glEnd();
}

void OGLWidget::resizeGL(int w, int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, (float)w/h, 0.01, 100.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0,0,5,0,0,0,0,1,0);
}

Now go back to the form and right click on the widget. Select promoted widgets and type in the promoted class name OGLWidget. Hit the add button and then promote. Now click on the background and go to its properties and change windowModality to ApplicationModel.

enter

and this is the result you should get

enter

the .pro file is

#-------------------------------------------------
#
# Project created by QtCreator 2015-07-20T15:15:29
#
#-------------------------------------------------

QT       += core gui opengl

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test2
TEMPLATE = app


SOURCES += main.cpp
        mainwindow.cpp 
    oglwidget.cpp

HEADERS  += mainwindow.h 
    oglwidget.h

FORMS    += mainwindow.ui

c++ – How do I render a triangle in QOpenGLWidget?