Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Ihmemies
Oct 6, 2012

FML. I have a map where keys are sorted with std::less<string> to alphabetical order.

NOW I realized this motherfucking exercise wants them in ASCII order.

So instead of:

code:
elastinen
Finlanders
Happoradio
That poo poo should be printed in

code:
Finlanders
Happoradio
elastinen
Order. :aaaaa:

Is there some automatic way to sort it or must I do some manual fuckery? :v:

Also why this stupid rear end project requires C++11 in compilation. I can't use contains() with map so my code is full of functions like

code:
bool Gigs::artists_contains_gig(string artist, string key_to_find) {
    auto ret = artists[artist]["Gigs"].count(key_to_find);
    while (ret) {
        return true;
        ret -= 1;
    }
    return false;
}


bool Gigs::artists_contains(string key_to_find) {
    auto ret = artists.count(key_to_find);
    while (ret) {
        return true;
        ret -= 1;
    }
    return false;
}

bool Gigs::stages_contains(string city, string stage, string key_to_find) {
    auto ret = stages[city][stage].count(key_to_find);
    while (ret) {
        return true;
        ret -= 1;
    }
    return false;
}
So.. great.................... :eng99:

Adbot
ADBOT LOVES YOU

Ihmemies
Oct 6, 2012

Thanks. This is my first c++ course and I really don't have that much of an idea what I'm actually doing :v: The previous one was in Python..

Even the data structure used was like "do whatever you want" so I just semi randomly figured out something which seems to work.

Ihmemies fucked around with this message at 07:25 on Oct 20, 2022

Ihmemies
Oct 6, 2012

gently caress this C++ course has loving pointers. Of course. I'm supposed to figure out the largest int of an array, and I only have access to the start and end pointer of the array. And I really don't understand anything. I barely managed to do a previous task where I had at least the size of the array provided. Now I don't have even that anymore. Just 2 pointers. WTF, what kind of sadist invented this poo poo

Ihmemies
Oct 6, 2012

I just wanted to vent, and I did knot know about any other thread. I have roughly 2 hours left to figure this out (it won't happen).

I'll probably have to :filez: a book about C, maybe it explains this in a way I can understand

Ihmemies fucked around with this message at 19:57 on Nov 15, 2022

Ihmemies
Oct 6, 2012

I understand. Maybe I can catch those segfaults when iterating through the array... so the program won't crash from segfault, instead it returns the largest value I've found so far.

Edit: can't feasibly catch segfaults, drat.

Ihmemies fucked around with this message at 20:09 on Nov 15, 2022

Ihmemies
Oct 6, 2012

It's supposed to print something like this:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 3 6 9
9
9
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 3 6 9

but I manage to get

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 3 6 9
9
0
-1887031104 32521 6 0 6 16 1240251648 592132058 -1889350432 32521 -1887035560 32521 -1887035768 32521 -1887034912 32521 -1887035200 32521 -1887915361 32521 -1887035560 32521 -1888119286 32521 -1887035192 32521 -1887035768 32521 -1887037120 32521

So it's not going too hot yet.

code:
int greatest_v1(int* itemptr, int size) {
    int i = 0;
    int largest = *(itemptr + i);
    while (i < size) {
        if (*(itemptr + i) > largest) {
            largest = *(itemptr + i);
        }
        i++;
    }

    return largest;
}

int greatest_v2(int* itemptr, int* endptr) {
    int i = 0;
    int largest = *(itemptr + i);

    while (*(itemptr + i) < *(endptr)) {
        if (*(itemptr + i) > largest) {
            largest = *(itemptr + i);
        }
        i++;
    }

    return largest;
}

void copy(int* itemptr, int* endptr, int* targetptr) {
    unsigned long int n = 0;
    int largest = *(itemptr + n);

    // calculate size of array
    while (*(itemptr + n) < *(endptr)) {
        if (*(itemptr + n) > largest) {
            largest = *(itemptr + n);
        }
        n++;
    }

    // copy array
    if (targetptr != nullptr)
    {
        for (size_t i = 0; i < n; i++) {
            *(targetptr + i) = *(itemptr + i);
        }
    }
}

Ihmemies
Oct 6, 2012

Well Actually I still have no idea but this seems to work better, while I was randomly trying to add more special characters to the mayhem:

code:
while (&(*(itemptr + i)) < endptr) {

Ihmemies
Oct 6, 2012

cheetah7071 posted:

yeah that would work, but once the test is over I would absolutely review what & and * actually do

I'm happy to explain it in a few hours once it isn't doing your homework for you

I'd rather write python at this point. Luckily there's only 2 weeks left in this most horrible course.

Ihmemies
Oct 6, 2012

Don’t worry. Next task is to implement a Book class with 16 mandatory methods, using pointers and recursion. The only choice is that I can use smart pointers instead of regular pointers if I want to. I have one week. :shepicide:

Ihmemies
Oct 6, 2012

Xarn posted:

When I was teaching programming, I would spend lot of time telling students to read their code as they wrote it, rather than what they think they wrote, or what they wish it did. If you actually read the code, the issue is obvious.

Multiple people have said this so far but I still have no idea. I never spot my own mistakes and rarely learn from them so most likely this one will go into the same ever growing pile of mistakes not learned from.

Ihmemies
Oct 6, 2012

Well the solution was to not use anything. Just remove everything :D
Thanks, and sorry for being so bad.

Anyways. I'm still battling an eternal struggle against on how to check for keys in a map. Is this legal?

Ihmemies
Oct 6, 2012

Dijkstracula posted:

Coming from Python, you'll find exceptions in C++ are intended for more "exceptional" cases.

std::map::find() returns a special value when the key is missing, and doesn't require a recent language version.

OK, I'll just do it with find() then. :sigh:

Ihmemies
Oct 6, 2012

Dijkstracula posted:

right, OP shouldn't feel that using `if (m.find(k) != m.end()) {...}` is a hack or an antipattern here.

I know. I was just curious.

This is I think how it should be done:

code:
std::shared_ptr<Chapter> Book::findChapter(const std::string &id) const {
    if (idstore.find(id) != idstore.end()) {
        return idstore.at(id);
    }
    cout << "Error: Not found: " << id << endl;
    return nullptr;
}
Any chance to get language specific color coding for code tag at the forums btw?

Ihmemies
Oct 6, 2012

Sweeper posted:

If you are new to cpp bookmark https://www.cppreference.com or add a quick search so you can type “cpp std::map” into url bar thing to lookup docs. I look things up all the time because c++ is inconsistent and many apis work in ways which make sense in the context of the standard, but aren’t intuitive. It’s a great site, bless the maintainers.

Yes. Our course even had some homework regarding using CPPref. I just forget to do this often enough.

Most of the Book was already presented ready for us. File reading, commandline handling etc. Only the implementation of Book classes methods was left for us. They gave us a ready struct we need to use for the chapters. I managed to do this not quite yet finished or even tested implementation yesterday: https://pastebin.com/uPDac0fA

At least some kind of recursion and shared pointers feel a lot easier to use when you can do whatever by yourself, and are not constrained too much by the strict limits set by coursework.

Ihmemies
Oct 6, 2012

roomforthetuna posted:

Is that Params monstrosity part of what they give you? Jesus.

Yes. Function parameters are given inside that params variable. The Chapter struct was given to us. Initially they were regular pointers like this:

code:
Chapter* parentChapter_ = nullptr;
std::vector<Chapter*> subchapters_;
but I changed them to smart pointers like below. They said we can change existing regular pointers to smart pointers if we want to. I'm not sure which smart pointer I should use so I randomly rolled shared_ptr and it seems to work at least. I think I won't be very good at freeing memory, so I hope that I can avoid freeing memory manually by using smart pointers instead, like this:

code:
std::shared_ptr<Chapter> parentChapter_ = nullptr;
std::vector<std::shared_ptr<Chapter>> subchapters_;
Then based on the chapter data we have to implement printouts to look like this:

code:
Book> contents
- 1. Introduction to the Basic Concepts ( 2 )
-   1. Definitions ( 5 )
-   2. The Basics ( 3 )
- 2. Fundamentals of Software Change ( 1 )
-   1. Software Change ( 2 )
-     1. Classification of Changes ( 2 )
-       1. Corrective Change ( 2 )
-       2. Adaptive Change ( 2 )
-       3. Perfective Change ( 4 )
-       4. Pretentive Change ( 3 )
-     2. The Importance of Categorizing Software Changes ( 6 )
-   2. Lehmans Laws ( 3 )
- 3. Program Understanding ( 3 )
-   1. Factors That Affect Understanding ( 2 )
-     1. Naming Style ( 3 )
-     2. Comments ( 2 )
-     3. Decomposition Mechanism ( 2 )
-   2. Documentation ( 4 )
- 4. Summary ( 3 )
Or

code:
Book> parents Adaptive 3
Adaptive has 3 parent chapters:
Classification
Fundamentals
Software Change
Etc.

Xarn posted:

An N-ary tree with cyclic references, what could possibly go wrong.

I am glad I have no idea, because I don't know what is an N-ary tree, or what are cycling references, or even what can possibly go wrong :v:

Ihmemies fucked around with this message at 21:22 on Nov 17, 2022

Ihmemies
Oct 6, 2012

Thanks! One reason also was (now when I'm re-reading this week's material) that they said "On this course, we will only get to know the type shared_ptr.". So it should be good enough for now. I guess I'd have to manuallydo a bunch of deleting in class destructor and maybe methods if I used regular pointers instead, and analyze with Valgrind if I succeed in that task or not.

Ihmemies
Oct 6, 2012

OddObserver posted:

Of more immediate significance: if your shared_ptr's form a cycle, they'll never get cleaned up.

(I apologize if my earlier comment was too snarky, I thought it was the code that you were provided...)

So if the program quits they stay in memory? Or those things stay in memory until the program closes? Is it bad if they stay in memory while the program is running?

I quickly read about trees and this page suggested to do first child/next sibling data structure: https://www.geeksforgeeks.org/generic-treesn-array-trees/

I guess that is impossible at this situation but from looking at it it looks more efficient?

Maybe I should replace the smart pointers with regular pointers and uhh do some manual deletion... :shepicide: Or maybe uhhhh make the uhh parent as a regular pointer and delete those in class destructor?

Ihmemies fucked around with this message at 21:54 on Nov 17, 2022

Ihmemies
Oct 6, 2012

Well all the the chapter data is needed as long as the created book class object? instance? whatever it's called is alive, since the data is read only once from file.

So I guess it's ok that the shared pointers keep existing in memory, as long as the instance is alive and needed. In class destructor, do I need to iterate through the all the chapters and manually delete the pointers, or change parentchapter type to weak pointer or something?

Seems they explained the cycles (I looked) but I forgot already about it. My memory is very bad in general.

Or should I change the parentchapters to unique pointers or something.. hmm.. I need to study more.

Ihmemies
Oct 6, 2012

cheetah7071 posted:

You almost never need to manually write a destructor. The default one covers you 99% of the time. The biggest exceptions in aware of are if you need to do something other than destroy objects for some reason, or if you're interfacing with C code and thus working with objects that don't have destructors

But in this case I need to clearly do something else than I'm doing, because of that circular shared ptr thing. I just need to figure out what would work better.

Ihmemies
Oct 6, 2012

Course said don't mix regular and smart pointers. So I won't be mixing them. Since I don't understand at all the differences between smart pointers, and I understand even less about how to manually release memory of regular pointers when they are not needed anymore, I'll just keep using the shared pointers. The user can buy more RAM if he runs out of it because of shared pointer linking. I don't give a drat.

Ihmemies
Oct 6, 2012

Sorry. This will use shared pointers for everything. I don't have the time or capacity to learn to do it any other way at this stage.

Ihmemies
Oct 6, 2012

Ideally I'd learn more about different types of smart pointers if I had the possibility to do a project from the ground up.

Now I don't understand enough about my program to refactor it again to work with different kind of pointers. I mean I got it to work "perfectly" as in the code gives expected printouts and it passes the tests.

Now the data sits in memory until program is closed, because of the linked shared pointers.

Anyways, uhh, maybe I could at least find a way to lessen the repetition. It has so many methods which have nearly the same contents, just copy pasted to other methods. Like printLongestInHierarchy vs printShortestInHierarchy, printParentsN, printSubchaptersN etc.

I have to figure some way to remove repetitive code, since it's penalized in grading...

Ihmemies
Oct 6, 2012

This week's C++ task said posted:

Many of the functions do similar things. You should think carefully, which utility functions to implement in order to avoid repeating code.


So. We have stuff like:
  • void close(Params& params), void open(Params& params)
  • void printParentsN(Params& params), void printSubchaptersN(Params& params)
  • void printLongestInHierarchy(Params& params), void printShortestInHierarchy(Params& params)

And I have been at the task, combining 2 methods to 1, avoiding repeating code, with ternary operators!

C++ code:
void Book::toggle_chapter(Params& params, bool isopen) const {
    string id = params.front();
    shared_ptr<Chapter> chapter = findChapter(id);

    // no chapter?
    if (chapter == nullptr) { return; }

    // open or close
    chapter->isopen_ = isopen;

    if (chapter->subchapters_.size() > 0) {
        for (auto& val : chapter->subchapters_) {
            // open
            if (isopen) {
                if (val->subchapters_.size() == 0 )
                    val->isopen_ = isopen;
            }
            // close subchapters
            else {
                toggle_chapter(vector<string> {val->id_}, isopen);
            }
        }
    }
}
C++ code:
void Book::print_pors_N(Params& params, bool isparents) const {
    string id = params.at(0);
    shared_ptr<Chapter> chapter = findChapter(id);

    // no chapter?
    if (chapter == nullptr) { return; }

    int level = stoi(params.at(1));

    // level must be at least 1.
    if (level < 1) {
        cout << "Error. Level can't be less than 1." << endl;
        return;
    }

    // no parent or subchapters?
    if (isparents
        ? chapter->parentChapter_ == nullptr
        : chapter->subchapters_.size() == 0
        ) {
        cout << id << " has no " << (isparents ? "parent " : "sub")
             << "chapters." << endl;
        return;
    }

    // collect a list of chapters so we can sort them before printing
    auto list = make_shared<vector<string>>();

    // populate list with parents or subchapters depending on what's wanted
    isparents
        ? get_parents(list, chapter, 0, level)
        : get_subchapters(list, id, 0, level);

    // sorts list to ASCII order with helper method compare
    std::sort (list->begin(), list->end(), compare);

    // Append to str and print result
    string result = id + " has " + to_string(list->size())
                  + (isparents ? " parent chapters:" : " subchapters:" );
    cout << result << endl;

    for (auto& val : *list) {
        cout << val << endl;
    }
}
C++ code:
void Book::print_sol_in_hierarchy(Params& params, bool islongest) const {
    string id = params.at(0);
    shared_ptr<Chapter> chapter = findChapter(id);

    // no chapter?
    if (chapter == nullptr) { return; }

    // get subchapters to depth n
    // TODO get_subchapters to work with inf depth
    auto list = make_shared<vector<string>>();
    get_subchapters(list, id, 0, 9999);

    string sol_id = id;
    int sol_len = chapter->length_;

    for (auto& val : *list) {
        if (islongest
            ? (idstore.at(val)->length_ > sol_len)
            : (idstore.at(val)->length_ < sol_len)
        ){
            sol_len = idstore.at(val)->length_;
            sol_id = val;
        }
    }

    // Append to str and print result. print() will be a c++23 feature
    string result = "With the length of " + to_string(sol_len) + ", "
                  + sol_id + " is the " + (islongest ? "longest" : "shortest")
                  + " chapter in " + (sol_id == id ? "their" : id + "'s")
                  + " hierarchy.";
    cout << result << endl;
}
Maybe I should stop, but I can't stop.

I have this like 7 times in different methods, still researching a way to combine them too. Maybe all the methods should call an utility method, which does this, and then that utility method calls the correct method? :v:

C++ code:
string id = params.front();
    shared_ptr<Chapter> chapter = findChapter(id);

    // no chapter?
    if (chapter == nullptr) { return; }
Although.. they don't strictly forbid us from editing the rest of the software:

E: nvm the comments in files forbid us from editing them: Student's don't touch this file.

This week's C++ task said posted:

You need not modify the ready-made functions. It is not necessary to understand the functionality of the modules Utils or Cli. However, since the topic of the round is modularity, this is a good example to be explored as a whole.

Ihmemies fucked around with this message at 20:56 on Nov 18, 2022

Ihmemies
Oct 6, 2012

So, I got feedback about a project and it said I need to initialize class variables. I was like ?????

I searched for a reason and apparently it is this:



If I have a map like this in class:

C++ code:
map<string, shared_ptr<Chapter>> idstore
How do I properly intialize it? I don't want to add any garbage to it which I have to get rid of later. Is this ok instead on the class header?

C++ code:
map<string, shared_ptr<Chapter>> idstore = {}
Or maybe this in Class constructor?

C++ code:
idstore = {}

Ihmemies
Oct 6, 2012

Twerk from Home posted:

Use initializer lists in your constructors, like this: https://en.cppreference.com/w/cpp/language/constructor

Well I have only one constructor and there's nothing in it. I just want to avoid that "intialize your class variables, minus 5 points" message I will get. I don't want to do anything complicated. I don't understand really a word about what that page says :v: That one class variable I use must be initialized properly, I just have to figure out how to do it. I don't want to add any data to the variable (map). I just want that the map exists, and is ready if someone ever wants to add data to it later.

Ihmemies
Oct 6, 2012

cheetah7071 posted:

For proper classes, instead of built-in types, they'll be constructed using the default constructor if you don't specify otherwise. Either they just wanted to to clarify that you were using the default constructor as like, a coding clarity thing, or they were talking about a member other than that map.

I had 2 uninitialized maps in the class header file. No other variables, only methods. They can’t possibly mean anything else.

Ihmemies
Oct 6, 2012

Finally a friend said what I must do.

If I create a vector like vector <string> to_sort; I must do vector <string> to_sort = {}; instead. If I create a map like map<string, shared_ptr<Chapter>> idstore; I have to do map<string, shared_ptr<Chapter>> idstore = {}; instead.

So the magic thing I must do is to add this after every vector and map to fix the problems:

C++ code:
= {};
I am glad I finally found the definitive answer I am looking for :ms:

Edit: and now I maybe finally perhaps understand? I must list instead all the class variables like this in the constructor, separated by ,

C++ code:
Book::Book() : running_id(0), idstore() { }
running_id is int and that 0 parameter sets it as 0... welp. I want back to python.

Ihmemies fucked around with this message at 11:32 on Nov 23, 2022

Ihmemies
Oct 6, 2012

Xarn posted:

do whatever you need to pass the course, but that's poo poo code if I ever saw one

The only issue is that I don’t know what to do. So I just do whatever I can find and understand. There is tons of info I can’t seem to understand by myself, about c++. I think I now understand how that works what I just pasted here, but I don’t know or I don’t understand any other ways to initialise class variables in class constructor. I was told that initializing class variables as empty with = {} in class header is even worse.

Please teach me master.

Ihmemies fucked around with this message at 12:52 on Nov 23, 2022

Ihmemies
Oct 6, 2012

leper khan posted:

https://en.cppreference.com/w/cpp/language/default_initialization

That should probably default initialize.

In general, you want unordered_map instead of map, but it likely doesn't matter a whole lot for your class.

So.. what should I do otherwise in my code? Something must be done otherwise since the way I initialise my class variables is apparently poo poo. Can you give me an understandable example? Thanks 🙏

Ihmemies
Oct 6, 2012

So what I’m doing is not really neccessary. And I am doing this only because for the sake of appearances, thank you.

Ihmemies
Oct 6, 2012

Well I don't really hate c++. It feels like I make a lot less erros with c++ than with python. I've read about new c++ features and I use them when possible. I think it's quite nice language to use. Especially print() coming in c++23 should be great instead of this something + something + something or << something << something << something.

It's just that c++ has so much stuff to get code working, that it's hard to remember or understand everything.

Ihmemies
Oct 6, 2012

Now I need to somehow learn to appreciate ANSI C. I need to print out numbers 1 7 11 13 17 19 23 29 31 37 41 43 47 49 53 59 61 67 71 73 77 79 83 89 91 97 in a loop. but the last one must have \n exactly after it, not allowed to print one space after it. My blood pressure is already rising. I guess I need to calculate the next number, and if there's no next number (after 97), I won't print a space after 97..

Ihmemies
Oct 6, 2012

Yes. I guess C forces to think. In python could just add it all to string and not print the last char of the string. Not so easy here..

Ihmemies
Oct 6, 2012

So, the last subject in our C++ course is quick GUI apps with Qt.

A course provided template project won't comile. A fresh Qt widget project won't compile. It just says:

code:
21:09:51: Starting: "/usr/bin/make" -j6
g++ -Wl,-rpath,/home/seppo/Programs/Qt/6.3.1/gcc_64/lib -Wl,-rpath-link,/home/seppo/Programs/Qt/6.3.1/gcc_64/lib -o find_dialog  main.o mainwindow.o moc_mainwindow.o   /home/seppo/Programs/Qt/6.3.1/gcc_64/lib/libQt6Widgets.so /home/seppo/Programs/Qt/6.3.1/gcc_64/lib/libQt6Gui.so /home/seppo/Programs/Qt/6.3.1/gcc_64/lib/libQt6Core.so -lpthread -lGL   
/usr/bin/ld: cannot find -lGL: No such file or directory
collect2: error: ld returned 1 exit status
make: *** [Makefile:216: find_dialog] Error 1
21:09:51: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project find_dialog (kit: Desktop Qt 6.3.1 GCC 64bit)
When executing step "Make"
21:09:51: Elapsed time: 00:00.
Wtf is "-lGL" :D It is really hard to find any info about whatever it is.

Edit. Well Google provided results instead of DGG. RIght after I figured out I better try another search engine. "apt install libgl1-mesa-dev"

Ihmemies
Oct 6, 2012

Now I need to make a Snake game with QT Widgets.

The game board must consist of squares, so I thought I'd make a bunch of squares with QGraphicsGridLayout and add square item objects to each grid. But, if I try to setLayout() a QGraphicsGridLayout inside a QWidget window, it says:

code:
game_window.cpp:41:15: Cannot initialize a parameter of type 'QLayout *' with an lvalue of type 'QGraphicsLinearLayout *'
qwidget.h:568:29: passing argument to parameter here
I have main menu, where I can open the game window with a click of a button. I can create a new QWidget window with the click of a button. Apparently QGraphicsWidget does't like to be a window, or otherwise needs something else. If I change QWidget to QGraphicsWidget a window won't open anymore when I click a button in the menu.

How do you create a QGraphicsWidget window in Qt? :v: I guess I need that to be able to use QGraphicsGridLayout. I just want a bunch of squares on screen, in a window, goddamnit.

Do I need to create a qgraphicswidget inside a qwidget so I can add some graphis grids? ? ? This is so complicated.

Ihmemies fucked around with this message at 16:17 on Nov 28, 2022

Ihmemies
Oct 6, 2012

Volguus posted:

Did you look at the documentation https://doc.qt.io/qt-6/qgraphicsgridlayout.html ? They have an example there on how to use it (add it to a QGraphicsScene ). Does this not work for you?

I have a mainwindow class, which is like a "launcher" for the game. Then I have game window, which uh I guess runs the game logic and tells the graphics what to do. Then the game_board class is actually which holds the graphics data?

So mainwindow -> gamewindow -> gameboard.

Gamewindow looks like this:

code:
#include "game_window.h"
#include "game_board.h"

#include <QGraphicsView>
#include <QDebug>

Game_window::Game_window(MainWindow *parent) :
    QWidget(parent, Qt::Window)
{
    //parent->hide();
    this->setStyleSheet("background-color: yellow;");

    QGraphicsScene scene;
    Game_board* window = new Game_board;
    scene.addItem(window);
    QGraphicsView view(&scene);
    view.resize(600, 600);

    parentWidget()->hide();
}

void Game_window::keyPressEvent(QKeyEvent* event) {
    if(event->key() == Qt::Key_Escape) {
        //qInfo() << "C++ Style Info Message";
        parentWidget()->show();
    }
}

Game_window::~Game_window()
{

}
And board like this:

code:
#include "game_board.h"
#include "square_item.h"

#include <QGraphicsGridLayout>

#include <QGridLayout>

Game_board::Game_board(QGraphicsWidget *parent) :
    QGraphicsWidget(parent, Qt::Window)
{
    QGraphicsGridLayout *grid = new QGraphicsGridLayout;

    Square_item* item = new Square_item;
    grid->addItem(item, 0, 0);

    item = new Square_item;
    grid->addItem(item, 1, 1);

    item = new Square_item;
    grid->addItem(item, 2, 2);

    item = new Square_item;
    grid->addItem(item, 1, 3);

    setLayout(grid);
}
Square_item is a QGraphicsItem which is supposed to hold the size and graphics etc. of the individual cell in the grid.. But I can't get anything to display and I have no idea why. Well I guess I just keep on experimenting and looking at the debugger, since it's really hard to figure out why nothing is being displayed on screen.

Ihmemies
Oct 6, 2012

Volguus posted:

Well, the first issue that i'm seeing is that the scene is destroyed after the Game_window constructor is finished. Game_window is a QMainWindow, right? Once the scene is created on the heap and you make the view the central widget of the main window, it should work. The parent of the view should be this.

Well, no. I guess I can have many QMainWindows?

Like, the launcher where user can define the game area size, like x,y, set seed etc. is a QMainWindow. Then when user has figured out what kind of game he wants to play, it launches the game_window.

Anyways I made view and scene class variables, and changed the game_window from qwidget to qmainwindow. Then I can use setcentralwidget and it puts something to the screen, finally:

code:
Game_window::Game_window(MainWindow *parent) :
    QMainWindow(parent, Qt::Window)
{
    //parent->hide();
    this->setStyleSheet("background-color: yellow;");

    scene = new QGraphicsScene();
    Game_board* board = new Game_board;
    scene->addItem(board);
    view = new QGraphicsView(scene);
    this->setCentralWidget(view);

    parentWidget()->hide();
}{
It doesn't put what I want to screen, but at least it's somehow doing something.. which is more than before. Thanks!

I mean it displays a tiny window with nothing, but I can close it and move around. Not ideal, yet:

Ihmemies fucked around with this message at 22:58 on Nov 28, 2022

Ihmemies
Oct 6, 2012

I have no idea at all what MDI is. I'm just trying to get this done. I don't think I've ever played a game where options are visible on the same screen as the actual game, they've always been in a separate options menu or something. And preferrably while playing, the option menu is hidden until ESC/F10 is pressed..

I don’t want the game view to be scrollable either. A snake game is nota hex strat game with a big scrollable map either. Well. Maybe I’ll eventually figure out a way to tell the computer what I want done.

Ihmemies fucked around with this message at 08:23 on Nov 29, 2022

Ihmemies
Oct 6, 2012

Well I finally figured out what was missing. The graphics item class constructor was empty, while it actually needed this to the constructor:

code:
setGraphicsItem(this);
Now to figure out how to get rid of that fuckin extra window.. I deeply hate Qt and it's "examples" and "documentation" at this point.

Or maybe it's intended. At least I'm getting some results now finally!

Adbot
ADBOT LOVES YOU

Ihmemies
Oct 6, 2012

drat python is so slow. I made this AoC day 8 puzzle in python first, then cpp. Python was 90ms, cpp 7ms. I tried to implement them the same way.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply